package com.tansun.easycare.rule.rulegroup.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import com.tansun.easycare.rule.datamodel.service.DataModelService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.kie.api.io.ResourceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.tansun.easycare.core.config.Global;
import com.tansun.easycare.core.utils.ResponseTable;
import com.tansun.easycare.rule.codeblock.service.RuleCodeblockService;
import com.tansun.easycare.rule.common.BomCreator;
import com.tansun.easycare.rule.common.Constant;
import com.tansun.easycare.rule.common.DataCache;
import com.tansun.easycare.rule.common.enums.ContentTypeEnum;
import com.tansun.easycare.rule.common.enums.RuleModelTypeFileEnum;
import com.tansun.easycare.rule.common.jfun.JFunCreator;
import com.tansun.easycare.rule.common.model.BaseBean;
import com.tansun.easycare.rule.common.model.BaseModel;
import com.tansun.easycare.rule.common.model.Bom;
import com.tansun.easycare.rule.common.model.BomField;
import com.tansun.easycare.rule.common.model.RuleDataCollention;
import com.tansun.easycare.rule.common.model.RuleExecParam;
import com.tansun.easycare.rule.common.model.RuleSetParamInfo;
import com.tansun.easycare.rule.common.rulebasebean.Action;
import com.tansun.easycare.rule.common.rulebasebean.Fact;
import com.tansun.easycare.rule.common.rulebasebean.RuleCollection;
import com.tansun.easycare.rule.common.service.DataBomService;
import com.tansun.easycare.rule.common.service.RuleDrlParseService;
import com.tansun.easycare.rule.common.service.impl.RuleBaseServiceImpl;
import com.tansun.easycare.rule.common.symbol.SymbolCreator;
import com.tansun.easycare.rule.common.symbol.WidgetCreator;
import com.tansun.easycare.rule.common.web.model.ProjectInfo;
import com.tansun.easycare.rule.datamodel.entity.RuleDataparams;
import com.tansun.easycare.rule.datamodel.service.RuleDataparamsService;
import com.tansun.easycare.rule.exception.BizException;
import com.tansun.easycare.rule.referencedata.entity.RuleReferenceData;
import com.tansun.easycare.rule.referencedata.service.RuleReferenceDataService;
import com.tansun.easycare.rule.rulegroup.dao.RuleEntryDao;
import com.tansun.easycare.rule.rulegroup.dao.RuleGroupDao;
import com.tansun.easycare.rule.rulegroup.dao.RuleGroupRefDao;
import com.tansun.easycare.rule.rulegroup.entity.RuleEntry;
import com.tansun.easycare.rule.rulegroup.entity.RuleGroup;
import com.tansun.easycare.rule.rulegroup.entity.RuleGroupRef;
import com.tansun.easycare.rule.rulegroup.model.ComplexRuleGroup;
import com.tansun.easycare.rule.rulegroup.model.OldRuleGroupRefNew;
import com.tansun.easycare.rule.rulegroup.model.RuleEditEntity;
import com.tansun.easycare.rule.rulegroup.model.RuleEntryReq;
import com.tansun.easycare.rule.rulegroup.model.RuleGroupInfo;
import com.tansun.easycare.rule.rulegroup.model.RuleGroupVO;
import com.tansun.easycare.rule.rulegroup.model.RuleRefVO;
import com.tansun.easycare.rule.rulegroup.model.RuleRefVOPage;
import com.tansun.easycare.rule.rulegroup.model.RuleSetDataInfo;
import com.tansun.easycare.rule.rulegroup.model.RuleSetExpressVO;
import com.tansun.easycare.rule.rulegroup.model.RuleSetVO;
import com.tansun.easycare.rule.rulegroup.model.SimpleRuleGroup;
import com.tansun.easycare.rule.rulegroup.service.RuleEntryService;
import com.tansun.easycare.rule.rulegroup.service.RuleGroupRefService;
import com.tansun.easycare.rule.rulegroup.service.RuleGroupService;
import com.tansun.easycare.rule.rulegroup.service.RuleParseDrl;
import com.tansun.easycare.rule.rulegroup.service.RuleParseExpService;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.model.RuleManageVO;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.easycare.rule.ruleproj.service.RuleProjectRankService;
import com.tansun.easycare.rule.ruletest.entity.RuleTest;
import com.tansun.easycare.rule.ruletest.model.RuleItem;
import com.tansun.easycare.rule.ruletest.model.TestDataModeVO;
import com.tansun.easycare.rule.ruletest.model.TestDatasetVO;
import com.tansun.easycare.rule.ruleversion.entity.RuleVersioninfo;
import com.tansun.easycare.rule.ruleversion.service.RuleVersioninfoService;
import com.tansun.easycare.rule.utils.DroolsExcuteDrlUtils;
import com.tansun.easycare.rule.utils.DroolsUtils;
import com.tansun.rule.common.RuleModelTypeEnum;
import com.tansun.rule.model.toolbean.RuleModel.RuleType;
import com.tansun.rule.utils.DroolsComplier;
import com.tansun.rule.utils.MClass;
import com.tansun.rule.utils.MField;
import com.tansun.rule.utils.RuleBomMapJsonConvert;
import com.tansun.rule.utils.StringUtils;

@Service
public class RuleGroupServiceImpl extends RuleBaseServiceImpl<RuleGroupDao, RuleGroup> implements RuleGroupService {

    @Autowired
    private DataBomService dataBomService;

	@Autowired
    private DataModelService dataModelService;

    @Autowired
    private RuleManageService ruleManageService;

    @Autowired
    private RuleVersioninfoService ruleVersioninfoService;

    @Autowired
    private RuleDrlParseService ruleDrlParseService;

    @Autowired
    private RuleReferenceDataService ruleReferenceDataService;

    @Autowired
    private RuleCodeblockService ruleCodeblockService;

    @Autowired
    private RuleGroupRefService ruleGroupRefService;

    @Autowired
    private RuleGroupRefDao ruleGroupRefDao;

//    @Autowired
//    private DataModelServiceImpl dataModelService;

    @Autowired
    private RuleEntryDao ruleEntryDao;
    @Autowired
    private RuleEntryService ruleEntryService;

    @Autowired
    private RuleProjectRankService ruleProjectRankService;

	@Autowired
	private  RuleDataparamsService  ruleDataparamsService;

    public static boolean isFuncModel = false;  //函数模式

    public static boolean isFilter = false;	//是否过滤目录



    @Override
    public String getRuleSetEditJson(RuleSetDataInfo ruleSetData) throws BizException {
        String jsondata = null;
        String  dataTarget =  ruleSetData.getType();
        String  projectCode =  ruleSetData.getProjectCode();
        String  rankrelationId =  ruleSetData.getRankrelationId();
        Map<String, Bom> map = new  HashMap<>();
        Map<String, Bom> alMap = dataBomService.findBomMapByProjectCode(projectCode,rankrelationId);
        String  selected =  ruleSetData.getSelected();
        if (!StringUtils.isEmpty(selected)) {
        	String[]  datasetNames =  StringUtils.split(selected, ",");
        	if (datasetNames != null ) {
        		for  (int i =0;i<datasetNames.length;i++) {
        			if (alMap.containsKey(datasetNames[i])) {
        				map.put(datasetNames[i],alMap.get(datasetNames[i]));
        			}
        		}
        	}
        	if(alMap.containsKey("func")){
        		map.put("func",alMap.get("func"));
			}
			if(alMap.containsKey("builtinParam")){
				map.put("builtinParam",alMap.get("builtinParam"));
			}


        }
        if (map.isEmpty()) {
        	map = alMap;
        }
        map.put("namelistinfo",initNameList());
        if ("indexBom".equals(dataTarget)) {
            jsondata = JSON.toJSONString(map);
        } else if ("handleBom".equals(dataTarget)) {
            jsondata = JSON.toJSONString(BomCreator.findInOut(map));
        } else if ("domain".equals(dataTarget)) {
            jsondata = JSON.toJSONString(this.dataBomService.findDomainByProjectCode(projectCode));
        } else if ("jfunc".equals(dataTarget)) {
            try {
                jsondata = JFunCreator.initJFun(ruleCodeblockService.genJFun(projectCode));
            } catch (Exception e) {
                throw new BizException(e, "");
            }
        } else if ("symbol".equals(dataTarget)) {
            //操作符
            jsondata = SymbolCreator.initSymbolGuide();
        } else if ("drlValue".equals(dataTarget)) {
            //值类型
            jsondata = WidgetCreator.initDrlConsValue();
        } else if ("topBom".equals(dataTarget)) {
            jsondata = BomCreator.initTopBom(map);
        } else if ("listtail".equals(dataTarget)) {
            jsondata = JSON.toJSONString(BomCreator.getListTailMap());
        }
        return jsondata;
    }
    private Bom initNameList() {
    	Bom namebom = new Bom();
		namebom.setId(StringUtils.generateTenUuid());
		namebom.setName("namelistinfo");
		namebom.setLabel("名单信息");
		namebom.setParamType("ALL");
		namebom.setDataType("namelistinfo");
		namebom.setType(BaseBean.TYPE_BOM);
		List<BomField> bomFields = new ArrayList<>();
		namebom.setBomFields(bomFields);
		BomField bf = new BomField();
		bf.setId(StringUtils.generateTenUuid());
		bf.setClassName("namelistinfo");
		bf.setType(BaseBean.OBJ_TYPE_FIELD);
		bf.setName("n1");
		bf.setLabel("中国红色通缉令人员");
		bf.setDataType("String");
		bomFields.add(bf);
		
		BomField bf1 = new BomField();
		bf1.setId(StringUtils.generateTenUuid());
		bf1.setClassName("namelistinfo");
		bf1.setType(BaseBean.OBJ_TYPE_FIELD);
		bf1.setName("n2");
		bf1.setLabel("国际刑警红色通缉令人员");
		bf1.setDataType("String");
		bomFields.add(bf1);
		
		BomField bf2 = new BomField();
		bf2.setId(StringUtils.generateTenUuid());
		bf2.setClassName("namelistinfo");
		bf2.setType(BaseBean.OBJ_TYPE_FIELD);
		bf2.setName("n3");
		bf2.setLabel("走私活动");
		bf2.setDataType("String");
		bomFields.add(bf2);
		
		return namebom;
    }
    @Autowired
    RuleParseExpService ruleParseExpService;
    /**
     * 规则保存
     * @param ruleEditEntity
     * @throws Exception
     */
    @Override
    public void saveOrUpdateRule(RuleEditEntity ruleEditEntity) throws Exception {
    	ruleEditEntity.getRuleManage().setStatus("1");
    	ruleEditEntity.getRuleManage().setModelType(RuleModelTypeEnum.GeneralRule.code);
    	RuleManage ruleManage = this.ruleManageService.saveOrUpdate(ruleEditEntity.getRuleManage());
    	this.saveOrUpdateRule(ruleManage, ruleEditEntity);

    }

    /**
     * 规则保存
     * @param ruleEditEntity
     * @throws Exception
     */
    @Override
    public void saveOrUpdateRule(RuleManage ruleManage,RuleEditEntity ruleEditEntity) throws Exception {
    	List<RuleGroup> ruleGroups= ruleEditEntity.getRuleGroups();
        RuleCollection rc = new RuleCollection();
        rc.setContentType(RuleType.policyrulegroup.toString());
        rc.setDrlName(ruleManage.getCode());
        rc.setVersion(ruleManage.getVersion());
        rc.setObjName(ruleManage.getName());
        Map<String, RuleReferenceData> refMap = new HashMap<String, RuleReferenceData>();
        int  idx =0;
        int  len  =  ruleGroups.size();
        //收集函数变量
        Map<String,RuleDataparams> funcparamMap = new HashMap<String,RuleDataparams>();
    	for(RuleGroup ruleGroup : ruleGroups) {
    		ruleGroup.setId(null);
    		ruleGroup.setProjectCode(ruleManage.getProjectCode());
    		ruleGroup.setManageId(ruleManage.getId());
    		ruleGroup.setVersion(ruleManage.getVersion());
    		ruleGroup.setCreateDate(new Date());
    		ruleGroup.setSeq(idx);
    		this.save(ruleGroup);
    		idx++;

    		//解析规则
    		com.tansun.easycare.rule.common.rulebasebean.RuleItem ruleItem = new com.tansun.easycare.rule.common.rulebasebean.RuleItem();
    		ruleItem.setSalience(len);
    		len--;
    		String evals = "";
    		String ruleEvals = ruleGroup.getEvals();
    		//解析规则条件及收集引用变量
    		if(!StringUtils.isEmpty(ruleEvals)) {
    			List<RuleSetExpressVO> ruleEvalSet = JSON.parseArray(ruleEvals, RuleSetExpressVO.class);
    			if( ruleEvalSet!=null &&
					!ruleEvalSet.isEmpty() &&
					ruleEvalSet.get(0).getConditions()!=null &&
					!ruleEvalSet.get(0).getConditions().isEmpty()) {
		    		evals = ruleParseExpService.parseFact(ruleEvalSet, false, this);
		    		this.ruleParseExpService.transformFactReference(ruleEvalSet, ruleManage, refMap,funcparamMap);//收集引用变量
//		    		ruleItem.getdWhen().getFirstFact().setContent(evals);
		    		Fact f = new Fact();
		    		f.setContent(evals);
		    		ruleItem.getdWhen().getEvalList().add(f);
    			}
    		}
    		String actionStr = "";
    		String ruleAction = ruleGroup.getActions();
    		//解析规则动作及收集引用变量
    		if(!StringUtils.isEmpty(ruleAction)) {
    			List<RuleSetExpressVO> ruleActionSet = JSON.parseArray(ruleAction, RuleSetExpressVO.class);
    			if( ruleActionSet!=null &&
					!ruleActionSet.isEmpty() &&
					ruleActionSet.get(0).getAction()!=null &&
					!ruleActionSet.get(0).getAction().isEmpty()) {
	        		actionStr = ruleParseExpService.parseAction(ruleActionSet, false, this);
	        		this.ruleParseExpService.transformFactReference(ruleActionSet, ruleManage, refMap,funcparamMap);//收集引用变量
	        		ruleItem.getdThen().getListAction().add(new Action(actionStr));
	        		ruleItem.getdThen().addLogsArr("droolsRuleLog.addLogs(\""+ruleManage.getCode()+"\",\"policyrulegroup\",\""+ruleManage.getName()+"\", drools,\"null\");");
	        		ruleItem.getdThen().addLogsArr("droolsRuleLog.addTracks(\""+ruleManage.getName()+"]["+ruleGroup.getRuleName()+"][IF\");");
    			}
    		}
    		rc.getListItem().add(ruleItem);
    		String ruleElseAction = ruleGroup.getElseActions();
    		//解析else  //如果条件存在， 那else中的条件与规则的条件相反来判断else操作  如果evals不存在条件， 则默认未必命中规则， else不解析
    		if(!StringUtils.isEmpty(ruleElseAction) && !StringUtils.isEmpty(evals)) {
    			List<RuleSetExpressVO> ruleElseActionSet = JSON.parseArray(ruleElseAction, RuleSetExpressVO.class);
    			if( ruleElseActionSet!=null &&
					!ruleElseActionSet.isEmpty() &&
					ruleElseActionSet.get(0).getAction()!=null &&
					!ruleElseActionSet.get(0).getAction().isEmpty()) {
		    		com.tansun.easycare.rule.common.rulebasebean.RuleItem ruleItem2 = new com.tansun.easycare.rule.common.rulebasebean.RuleItem();
//		    		ruleItem2.getdWhen().getFirstFact().setContent("("+evals+")==false");
		    		Fact f = new Fact();
		    		f.setContent("("+evals+")==false");
		    		ruleItem2.getdWhen().getEvalList().add(f);

		    		String elseStr = ruleParseExpService.parseAction(ruleElseActionSet, false, this);
		    		this.ruleParseExpService.transformFactReference(ruleElseActionSet, ruleManage, refMap,funcparamMap);//收集引用变量
		    		ruleItem2.getdThen().getListAction().add(new Action(elseStr));
		    		ruleItem2.getdThen().addLogsArr("droolsRuleLog.addLogs(\""+ruleManage.getCode()+"\",\"policyrulegroup\",\""+ruleManage.getName()+"\", drools,\"null\");");
		    		ruleItem2.getdThen().addLogsArr("droolsRuleLog.addTracks(\""+ruleManage.getName()+"]["+ruleGroup.getRuleName()+"][ELSE\");");
		    		ruleItem.setActivationGroup(ruleGroup.getId());
		    		ruleItem2.setActivationGroup(ruleGroup.getId());
		    		rc.getListItem().add(ruleItem2);
    			}
    		}
    	}
		//保存函数变量
        List<RuleDataparams> ruleParamdatas = new ArrayList<>(funcparamMap.values());
        this.ruleReferenceDataService.saveReferenceDataFuncRef(ruleParamdatas,ruleManage);
    	this.ruleReferenceDataService.saveReferenceData(refMap);
    	String drlContent =  DroolsUtils.convert2DrlTxt(rc);
        RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
        ruleVersioninfo.init(ruleManage, drlContent);
        ruleVersioninfo.setProjectCode(ruleManage.getProjectCode());
        ruleVersioninfo.setDatasetNames(ruleEditEntity.getDatasetNames());
        this.ruleVersioninfoService.save(ruleVersioninfo);
        DataCache.ruleSetEffectChange(ruleManage.getProjectCode());
    }

    @Override
  	public  void  updateSetParam(String manageId,RuleSetParamInfo newSetParamInfo,RuleSetParamInfo oldParamInfo,boolean  setFlag) throws Exception {
		 RuleManage  ruleManage =  this.ruleManageService.get(manageId);
		 RuleGroup   groupInfo = new  RuleGroup();
		 groupInfo.setManageId(manageId);
		 groupInfo.setVersion(ruleManage.getActiveVersion());
		 List<RuleGroup> list = this.findList(groupInfo);
	     RuleCollection rc = new RuleCollection();
	     rc.setContentType(RuleType.policyrulegroup.toString());
	     rc.setDrlName(ruleManage.getCode());
         rc.setVersion(ruleManage.getVersion());
         rc.setObjName(ruleManage.getName());
    	 for(RuleGroup ruleGroup : list) {
            String  factStr  =  ruleGroup.getEvals();
        	List<RuleSetExpressVO> evalList = this.ruleParseExpService.parseFactExpress(factStr, newSetParamInfo,oldParamInfo, setFlag);
        	ruleGroup.setEvals(JSON.toJSONString(evalList));
        	String  actStr =ruleGroup.getActions();
        	List<RuleSetExpressVO> actList = this.ruleParseExpService.parseFactExpress(actStr, newSetParamInfo,oldParamInfo, setFlag);
        	ruleGroup.setActions(JSON.toJSONString(actList));
        	String  elsActStr =ruleGroup.getElseActions();
        	List<RuleSetExpressVO> elsList = this.ruleParseExpService.parseFactExpress(elsActStr, newSetParamInfo,oldParamInfo, setFlag);
        	ruleGroup.setElseActions(JSON.toJSONString(elsList));
    		this.save(ruleGroup);
    		com.tansun.easycare.rule.common.rulebasebean.RuleItem ruleItem = new com.tansun.easycare.rule.common.rulebasebean.RuleItem();
    		String evals = "";
    		String ruleEvals = ruleGroup.getEvals();
    		if(!StringUtils.isEmpty(ruleEvals)) {
    			List<RuleSetExpressVO> ruleEvalSet = JSON.parseArray(ruleEvals, RuleSetExpressVO.class);
    			if( ruleEvalSet!=null &&
					!ruleEvalSet.isEmpty() &&
					ruleEvalSet.get(0).getConditions()!=null &&
					!ruleEvalSet.get(0).getConditions().isEmpty()) {
		    		evals = ruleParseExpService.parseFact(ruleEvalSet, false, this);
		    		Fact f = new Fact();
		    		f.setContent(evals);
		    		ruleItem.getdWhen().getEvalList().add(f);
    			}
    		}
    		String ruleActions = ruleGroup.getActions();
    		if(!StringUtils.isEmpty(ruleActions)) {
    			List<RuleSetExpressVO> ruleActionSet = JSON.parseArray(ruleActions, RuleSetExpressVO.class);
    			if( ruleActionSet!=null &&
					!ruleActionSet.isEmpty() &&
					ruleActionSet.get(0).getAction()!=null &&
					!ruleActionSet.get(0).getAction().isEmpty()) {
	        		String actionStr = ruleParseExpService.parseAction(ruleActionSet, false, this);
	        		ruleItem.getdThen().getListAction().add(new Action(actionStr));
	        		ruleItem.getdThen().addLogsArr("droolsRuleLog.addLogs(\""+ruleManage.getCode()+"\",\"policyrulegroup\",\""+ruleManage.getName()+"\", drools,\"null\");");
	        		ruleItem.getdThen().addLogsArr("droolsRuleLog.addTracks(\""+ruleManage.getName()+"]["+ruleGroup.getRuleName()+"][IF\");");
    			}
    		}
    		rc.getListItem().add(ruleItem);
    		String ruleElseActions = ruleGroup.getElseActions();
    		if(!StringUtils.isEmpty(ruleElseActions) && !StringUtils.isEmpty(evals)) {
    			List<RuleSetExpressVO> ruleElseActionSet = JSON.parseArray(ruleElseActions, RuleSetExpressVO.class);
    			if( ruleElseActionSet!=null &&
					!ruleElseActionSet.isEmpty() &&
					ruleElseActionSet.get(0).getAction()!=null &&
					!ruleElseActionSet.get(0).getAction().isEmpty()) {
		    		com.tansun.easycare.rule.common.rulebasebean.RuleItem ruleItem2 = new com.tansun.easycare.rule.common.rulebasebean.RuleItem();
		    		Fact f = new Fact();
		    		f.setContent("("+evals+")==false");
		    		ruleItem2.getdWhen().getEvalList().add(f);

		    		String elseStr = ruleParseExpService.parseAction(ruleElseActionSet, false, this);
		    		ruleItem2.getdThen().getListAction().add(new Action(elseStr));
		    		ruleItem2.getdThen().addLogsArr("droolsRuleLog.addLogs(\""+ruleManage.getCode()+"\",\"policyrulegroup\",\""+ruleManage.getName()+"\", drools,\"null\");");
		    		ruleItem2.getdThen().addLogsArr("droolsRuleLog.addTracks(\""+ruleManage.getName()+"]["+ruleGroup.getRuleName()+"][ELSE\");");
		    		ruleItem.setActivationGroup(ruleGroup.getId());
		    		ruleItem2.setActivationGroup(ruleGroup.getId());
		    		rc.getListItem().add(ruleItem2);
    			}
    		}
    	}
    	String drlContent =  DroolsUtils.convert2DrlTxt(rc);
		RuleVersioninfo  versInfo  = new RuleVersioninfo();
		versInfo.setManageId(ruleManage.getId());
		versInfo.setVersion(ruleManage.getActiveVersion());
	    List<RuleVersioninfo> vList =	this.ruleVersioninfoService.findList(versInfo);
	    if (vList != null && vList.size()>0) {
	    	RuleVersioninfo  ruleVer = vList.get(0);
	    	ruleVer.setRuleContent(drlContent);
	    	this.ruleVersioninfoService.save(ruleVer);
	    }
    }

//    @Override
//    public TestDataModeVO saveOrUpdateGeneralRule(RuleGroup ruleGroup) throws BizException {
//        String manageId = ruleGroup.getManageId();//指当前规则的manage 不是规则集的
//        TestDataModeVO testDataModeVO = null;//返回搜集的引用数据
//        if (StringUtils.isEmpty(manageId)) {
//        	Date date = new Date();
//            RuleManage ruleManage = new RuleManage();
//            ruleManage.setRankRelationId(ruleGroup.getRankRelationId());
//            ruleManage.setName(ruleGroup.getRuleName());
//            ruleManage.setModelType(RuleModelTypeEnum.GeneralRule.code);
//            ruleManage.setProjectCode(ruleGroup.getProjectCode());
//            ruleManage.setCreateDate(date);
//            this.ruleManageService.saveOrUpdate(ruleManage);
//            ruleGroup.setVersion(ruleManage.getVersion());
//            ruleGroup.setManageId(ruleManage.getId());
//            ruleGroup.setCreateDate(date);
//            this.save(ruleGroup);
//
//
//            /**drl保存在ruleversioninfo**/
//            String ruleDrl = getRuleDrl(ruleManage,ruleGroup);
//            RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
//            ruleVersioninfo.init(ruleManage, ruleDrl);
//            this.ruleVersioninfoService.save(ruleVersioninfo);
//            /**获取关联数据，用于单笔测试，输入输出数据显示**/
//    		try {
//				testDataModeVO = this.ruleDrlParseService.getDataMode(ruleDrl, ruleGroup.getProjectCode());
//			} catch (Exception e) {
//				throw new BizException(e,"");
//			}
//            this.saveRuleRef(testDataModeVO, ruleManage);
//        } else {
//            RuleManage ruleManage = this.ruleManageService.get(manageId);
//            ruleManage.setName(ruleGroup.getRuleName());
//            ruleManage.setStatus(Constant.RULE_STATUS_NORMAL);
//            this.ruleManageService.saveOrUpdate(ruleManage);
//            ruleGroup.setVersion(ruleManage.getVersion());
//            ruleGroup.setId(null);
//
//            this.save(ruleGroup);
//            /**drl保存在ruleversioninfo**/
//            String ruleDrl = getRuleDrl(ruleManage,ruleGroup);
//            RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
//            ruleVersioninfo.init(ruleManage, ruleDrl);
//            this.ruleVersioninfoService.save(ruleVersioninfo);
//            /**获取关联数据，用于单笔测试，输入输出数据显示**/
//    		try {
//				testDataModeVO = this.ruleDrlParseService.getDataMode(ruleDrl, ruleGroup.getProjectCode());
//			} catch (Exception e) {
//				throw new BizException(e,"");
//			}
//            this.saveRuleRef(testDataModeVO, ruleManage);
//        }
//        return testDataModeVO;
//    }

    /**
     * 规则删除操作
     */
    @Override
    public void delGeneralRule(String manageId) throws BizException {
        RuleManage ruleManage = this.ruleManageService.get(manageId);
        RuleGroup groupInfo = new RuleGroup();
        groupInfo.setManageId(ruleManage.getId());
        groupInfo.setVersion(ruleManage.getVersion());
        List<RuleGroup> list = this.findList(groupInfo);
        if (list != null && list.size() > 0) {
        	RuleGroup group = list.get(0);
        	 RuleGroupRef ruleGroupRef = new RuleGroupRef();
             ruleGroupRef.setRuleId(group.getId());
             List<RuleGroupRef> ruleGroupRefList = this.ruleGroupRefService.findList(ruleGroupRef);
             if(ruleGroupRefList!=null && ruleGroupRefList.size()>0) {
             	for(RuleGroupRef arg0:ruleGroupRefList) {
             		this.ruleGroupRefService.delete(arg0);
             	}
             }
            this.delete(list.get(0));
//            RuleGroup  ruleInfo = new  RuleGroup();
//            ruleInfo.setManageId(manageId);
//            List<RuleGroup> rList =this.findList(ruleInfo);
//            if (rList == null || rList.size()==0){
//               this.ruleManageService.delete(ruleManage);
//            }else {
//               RuleGroup  maxRule = null;
//               Integer  iv = null;
//               Integer  mv = null;
//               for (RuleGroup tmpGroup :rList){
//            	    if (maxRule != null){
//            	    	iv = Integer.parseInt(maxRule.getVersion().substring(1));
//            	    	mv = Integer.parseInt(tmpGroup.getVersion().substring(1));
//            	    	if (mv >iv)
//            	    		maxRule = tmpGroup;
//            	    }else{
//            	    	maxRule = tmpGroup;
//            	    }
//               }
//               if (maxRule != null){
//                  ruleManage.setVersion(maxRule.getVersion());
//                  this.ruleManageService.save(ruleManage);
//               }
//            }
//        }else {
            //       	this.ruleManageService.delete(ruleManage);
        }
        this.ruleManageService.delete(ruleManage);
        this.updateRuleGroupWithoutVersion(ruleManage);
    }

    public void saveOrUpdate(RuleGroup ruleGroup) throws BizException {
    	String manageId = ruleGroup.getManageId();//规则集的manageId
    	RuleManage ruleGroupManage = this.ruleManageService.get(manageId);//查找规则集的ruleManage
    	TestDataModeVO testDataModeVO = null;//搜集引用数据
    	Integer salience = ruleGroupManage.getCountSalience() == null ? 999999 :ruleGroupManage.getCountSalience()-1;
    	String projectCode = ruleGroupManage.getProjectCode();
    	RuleGroupRef ref = null;
    	if(StringUtils.isEmpty(ruleGroup.getId())) {
        	ref = new RuleGroupRef();
        	ref.setProjectCode(projectCode);
    		ruleGroup.setManageId(null);//manage置空，新曾一个规则的manage
    		ruleGroup.setSort(salience);
    		ruleGroup.setProjectCode(projectCode);
//    		testDataModeVO = this.saveOrUpdateGeneralRule(ruleGroup);//在规则中插入规则

        	ref.setManageId(manageId);
    		ref.setRuleId(ruleGroup.getManageId());//将规则ID 替换称规则的manageId
    		ref.setVersion(ruleGroupManage.getVersion());//规则集版本
    		ref.setSort(salience);
    		ref.setEntryId(ruleGroup.getEntryId());
    		ruleGroupRefService.save(ref);

    		ruleGroupManage.setCountSalience(salience);
    		this.ruleManageService.save(ruleGroupManage);
            this.saveRuleRef(testDataModeVO, ruleGroupManage);//保存规则集的引用数据
    	}else {
    		ref = ruleGroupRefService.get(ruleGroup.getRefId());
    		RuleManage rm = this.ruleManageService.get(ref.getRuleId());//获取规则的manage，与规则集的manage不同
    		rm.setName(ruleGroup.getRuleName());
    		rm = this.ruleManageService.saveOrUpdate(rm);

    		ruleGroup.setVersion(rm.getVersion());
    		ruleGroup.setId(null);
    		ruleGroup.setManageId(rm.getId());
        	salience = rm.getCountSalience() == null ? 999999 :rm.getCountSalience()-1;
    		ruleGroup.setSort(salience);
    		ruleGroup.setProjectCode(projectCode);
    		this.save(ruleGroup);
            /**drl保存在ruleversioninfo**/
            String ruleDrl = getRuleDrl(rm,ruleGroup);
            RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
            ruleVersioninfo.init(rm, ruleDrl);
            this.ruleVersioninfoService.save(ruleVersioninfo);
    		/**保存关联关系，用于单笔测试，输入输出数据显示**/
    		try {
				testDataModeVO = this.ruleDrlParseService.getDataMode(ruleDrl, projectCode);
			} catch (Exception e) {
				throw new BizException(e,"");
			}
    		this.saveRuleRef(testDataModeVO, ruleGroupManage);//保存规则集 的引用数据
    		this.saveRuleRef(testDataModeVO, rm);//保存规则 的引用数据
    	}
    }
    /**
     * 规则生效，drl重新保存
     * @param ruleIds 规则的manageId
     */
    @Override
    public void updateRuleGoupDRL(List<String> ruleIds,String projectCode) {
    	DataCache.ruleSetEffectChange(projectCode);//规则生效时，缓存清理
        //规则集对应修改，版本不更新，drl改变
        List<String> manageIdList = ruleGroupRefService.findManageIdByRuleIds(ruleIds);
        if(manageIdList!=null&&manageIdList.size()>0){
            for(String manageIdStr : manageIdList){
                this.updateRuleGroupWithoutVersion(manageIdStr);
            }
        }
    }
    /**
     * 规则集-规则保存
     * @param ruleGroup
     * @exception BizException
     */
//    @Override
//    public void saveOrUpdate(RuleGroup ruleGroup) throws BizException {
//        String manageId = ruleGroup.getManageId();
//        RuleManage ruleManage = this.ruleManageService.get(manageId);
//        //this.ruleManageService.saveOrUpdate(ruleManage);
//        String projectCode = ruleManage.getProjectCode();
//        String manageVersion = ruleManage.getVersion();
//
//        //校验规则名称重复
//        RuleGroup search = new RuleGroup();
//        search.setManageId(manageId);
//        search.setProjectCode(projectCode);
//        search.setVersion(manageVersion);
//        List<RuleGroup> ruleGroupList = this.findList(search);
//        if (null == ruleGroupList || ruleGroupList.size() < 1) {
//            //新增规则集时列表为空
//        } else {
//            for (RuleGroup group : ruleGroupList) {
//                if (group.getRuleName().equals(ruleGroup.getRuleName()) && !group.getId().equals(ruleGroup.getId())) {
//                    throw new BizException("E-000111");
//                }
//            }
//        }
//
//        ruleManage.setStatus(Constant.RULE_STATUS_NORMAL);
//        ruleGroup.setProjectCode(projectCode);
//        ruleGroup.setVersion(manageVersion);
//        ruleGroup.setSalience(0);
//        Integer countSalience = ruleManage.getCountSalience();
//        if (StringUtils.isEmpty(ruleGroup.getId())) {
//            ruleGroup.setSort(countSalience - 1);
//            ruleGroup.setGroupCode(this.generalCodeByType("R", ruleManage.getProjectCode()));
//            ruleManage.setCountSalience(countSalience - 1);
//            this.ruleManageService.save(ruleManage);
//        }
//        this.save(ruleGroup);
//    }


    /**
     * 规则集保存
     */
    @Override
    public RuleManage saveOrUpdateRuleGroup(String manageId) throws BizException {
    	//保存ruleManage，主要是更新版本
        RuleManage ruleManage = this.ruleManageService.get(manageId);
        updateRuleGroup(ruleManage);
        return ruleManage;
    }

    /**
     * 保存简易规则集发布drl
     * @param ruleManage
     * @throws BizException
     */
    @Override
    public void saveOrUpdateSimpleRuleGroup(String manageId) throws BizException {
    	//保存ruleManage，主要是更新版本
    	RuleManage ruleManage = this.ruleManageService.get(manageId);
        String oldVersion = ruleManage.getVersion();
        ruleManage.setStatus(Constant.RULE_STATUS_NORMAL);
        if(oldVersion.contains("_modify")) {
            ruleManage.setVersion(ruleManage.getVersion().replace("_modify", ""));
            this.ruleManageService.save(ruleManage);
        }else {
        	this.ruleManageService.saveOrUpdate(ruleManage);
        }

        //简易规则集容器
        SimpleRuleGroup simpleRuleGroup = new SimpleRuleGroup();
        simpleRuleGroup.setRuleManage(ruleManage);

        //查询老版关联关系
        RuleGroupRef refCon = new RuleGroupRef();
        refCon.setManageId(manageId);
        refCon.setVersion(oldVersion);
        List<RuleGroupRef> ruleref =  ruleGroupRefService.findList(refCon);

        //查询老版本规则
        RuleGroup ruleGroup = new RuleGroup();
        ruleGroup.setManageId(manageId);
        ruleGroup.setVersion(oldVersion);
        List<RuleGroup> ruleList = this.ruleGroupRefService.findRefRuleManage(ruleGroup);
        List<RuleEditEntity> rules = new ArrayList<>();
        for(RuleGroup rg:ruleList) {
        	RuleManage rm = new RuleManage();
        	rm.setId(rg.getManageId());
			rm.setName(rg.getRuleName());
			rm.setProjectCode(rg.getProjectCode());
			rm.setVersion(rg.getVersion());
			RuleEditEntity entity = new RuleEditEntity();
			entity.setRuleManage(rm);
			RuleGroup newRG = new RuleGroup();
			newRG.setManageId(rm.getId());
			newRG.setVersion(rm.getVersion());
			List<RuleGroup> ruleGroups = this.findList(newRG);
			entity.setRuleGroups(ruleGroups);
			rules.add(entity);
        }
        simpleRuleGroup.setRules(rules);

        //更改版本，重新保存RuleGroupRef
        String newVersion = ruleManage.getVersion();
        for (RuleGroupRef ruleGroupRef : ruleref) {
        	ruleGroupRef.setId(null);
        	ruleGroupRef.setVersion(newVersion);
		}
        this.ruleGroupRefService.insertBatch(ruleref);
        try {
        	this.saveOrUpdateRule(simpleRuleGroup);
        }catch(Exception e) {
        	throw new BizException("",e.getMessage());
        }

    }

    /**
     * 规则集保存，主要是drl版本生成
     * @param ruleEditEntity
     * @throws Exception
     */
    public void saveOrUpdateRule(SimpleRuleGroup simpleRuleGroup) throws Exception {
    	RuleManage ruleManage = simpleRuleGroup.getRuleManage();
    	List<RuleEditEntity> rules = simpleRuleGroup.getRules();
        RuleCollection rc = new RuleCollection();
        rc.setContentType(RuleType.policyrulegroup.toString());
        rc.setDrlName(ruleManage.getCode());
        rc.setVersion(ruleManage.getVersion());
        rc.setObjName(ruleManage.getName());
        Map<String, RuleReferenceData> refMap = new HashMap<String, RuleReferenceData>();
        Map<String,RuleDataparams> funcparamMap = new HashMap<String,RuleDataparams>();
    	for(RuleEditEntity entity : rules) {
    		RuleManage rm = entity.getRuleManage();
    		List<RuleGroup> rgList = entity.getRuleGroups();
    		for(RuleGroup ruleGroup:rgList) {
        		ruleGroup.setProjectCode(ruleManage.getProjectCode());
        		ruleGroup.setManageId(ruleManage.getId());
        		ruleGroup.setVersion(ruleManage.getVersion());
        		ruleGroup.setCreateDate(new Date());
        		//解析规则
        		com.tansun.easycare.rule.common.rulebasebean.RuleItem ruleItem = new com.tansun.easycare.rule.common.rulebasebean.RuleItem();
        		ruleItem.setRuleName(rm.getName()+"]["+ruleGroup.getRuleName());
        		String evals = "";
        		String ruleEvals = ruleGroup.getEvals();
        		//解析规则条件及收集引用变量
        		if(!StringUtils.isEmpty(ruleEvals)) {
        			List<RuleSetExpressVO> ruleEvalsSet = JSON.parseArray(ruleEvals, RuleSetExpressVO.class);
        			if( ruleEvalsSet!=null &&
    					!ruleEvalsSet.isEmpty() &&
    					ruleEvalsSet.get(0).getConditions()!=null &&
    					!ruleEvalsSet.get(0).getConditions().isEmpty()) {
	    	    		evals = ruleParseExpService.parseFact(ruleEvalsSet, false, this);
	    	    		this.ruleParseExpService.transformFactReference(ruleEvalsSet, ruleManage, refMap, funcparamMap);//收集引用变量
	    	    		ruleItem.getdWhen().getFirstFact().setContent(evals);
        			}
        		}
        		String ruleActions = ruleGroup.getActions();
        		//解析规则动作及收集引用变量
        		if(!StringUtils.isEmpty(ruleActions)) {
        			List<RuleSetExpressVO> ruleActionSet = JSON.parseArray(ruleActions, RuleSetExpressVO.class);
        			if( ruleActionSet!=null &&
    					!ruleActionSet.isEmpty() &&
    					ruleActionSet.get(0).getAction()!=null &&
    					!ruleActionSet.get(0).getAction().isEmpty()) {
	            		String actionStr = ruleParseExpService.parseAction(ruleActions, false, this);
	            		this.ruleParseExpService.transformFactReference(ruleActions, ruleManage, refMap, funcparamMap);//收集引用变量
	            		ruleItem.getdThen().getListAction().add(new Action(actionStr));
        			}
        		}
        		rc.getListItem().add(ruleItem);
        		String ruleElseActions = ruleGroup.getElseActions();
        		//解析else  //如果条件存在， 那else中的条件与规则的条件相反来判断else操作  如果evals不存在条件， 则默认未必命中规则， else不解析
        		if(!StringUtils.isEmpty(ruleElseActions) && !StringUtils.isEmpty(evals)) {
        			List<RuleSetExpressVO> ruleElseActionSet = JSON.parseArray(ruleElseActions, RuleSetExpressVO.class);
        			if( ruleElseActionSet!=null &&
    					!ruleElseActionSet.isEmpty() &&
    					ruleElseActionSet.get(0).getAction()!=null &&
    					!ruleElseActionSet.get(0).getAction().isEmpty()) {
	        			com.tansun.easycare.rule.common.rulebasebean.RuleItem ruleItem2 = new com.tansun.easycare.rule.common.rulebasebean.RuleItem();
	        			ruleItem2.getdWhen().getFirstFact().setContent("("+evals+")==false");
	    	    		ruleItem2.setRuleName(rm.getName()+"]["+ruleGroup.getRuleName());

	    	    		String elseStr = ruleParseExpService.parseAction(ruleElseActions, false, this);
	    	    		this.ruleParseExpService.transformFactReference(ruleElseActions, ruleManage, refMap, funcparamMap);//收集引用变量
	    	    		ruleItem2.getdThen().getListAction().add(new Action(elseStr));
	    	    		rc.getListItem().add(ruleItem2);
    	    		}
        		}
    		}
    	}
		//保存函数变量
        List<RuleDataparams> ruleParamdatas = new ArrayList<>(funcparamMap.values());
        this.ruleReferenceDataService.saveReferenceDataFuncRef(ruleParamdatas,ruleManage);
    	this.ruleReferenceDataService.saveReferenceData(refMap);
    	String drlContent =  DroolsUtils.convert2DrlTxt(rc);
        RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
        ruleVersioninfo.init(ruleManage, drlContent);
        ruleVersioninfo.setProjectCode(ruleManage.getProjectCode());
        this.ruleVersioninfoService.save(ruleVersioninfo);
    }

    /**
     * 规则集发布版本生成drl
     * @param ruleManage 已查询出的完整ruleManage
     * @throws BizException
     */
    public void updateRuleGroup(RuleManage ruleManage) throws BizException {
    	//保存ruleManage，主要是更新版本
        String manageId = ruleManage.getId();
        String oldVersion = ruleManage.getVersion();
        ruleManage.setStatus(Constant.RULE_STATUS_NORMAL);
        if(oldVersion.contains("_modify")) {
            ruleManage.setVersion(ruleManage.getVersion().replace("_modify", ""));
            String activeVersion = ruleManage.getActiveVersion();
            if(StringUtils.isNotEmpty(activeVersion) && activeVersion.contains("_modify")) {
                ruleManage.setActiveVersion(activeVersion.replace("_modify", ""));
            }
            this.ruleManageService.save(ruleManage);
        }else {
        	this.ruleManageService.saveOrUpdate(ruleManage);
        }

        //查询老版本RuleEntry
        RuleEntry ruleEntry = new RuleEntry();
        ruleEntry.setManageId(manageId);
        ruleEntry.setVersion(oldVersion);
        List<RuleEntry> ruleEntryList = this.ruleEntryService.findList(ruleEntry);

        //查询老版本RuleGroupRef关联关系
        RuleGroupRef refCon = new RuleGroupRef();
        refCon.setManageId(manageId);
        refCon.setVersion(oldVersion);
        List<RuleGroupRef> ruleref =  ruleGroupRefService.findList(refCon);

        //查询老版本规则
        String newVersion = ruleManage.getVersion();
        RuleGroup groupInfo = new RuleGroup();
        groupInfo.setManageId(manageId);
        groupInfo.setVersion(oldVersion);
        List<RuleGroup> ruleList = this.ruleGroupRefService.findRefRuleManage(groupInfo);
        List<RuleEditEntity> rules = new ArrayList<>();
        for(RuleGroup rg:ruleList) {
        	RuleManage rm = new RuleManage();
        	rm.setId(rg.getManageId());
			rm.setName(rg.getRuleName());
			rm.setProjectCode(rg.getProjectCode());
			rm.setVersion(rg.getVersion());
			RuleEditEntity entity = new RuleEditEntity();
			entity.setRuleManage(rm);
			RuleGroup newRG = new RuleGroup();
			newRG.setManageId(rm.getId());
			newRG.setVersion(rm.getVersion());
			List<RuleGroup> ruleGroups = this.findList(newRG);
			for(RuleGroup ruleGroup:ruleGroups) {
				ruleGroup.setRefId(rg.getRefId());
				ruleGroup.setEntryId(rg.getEntryId());
				ruleGroup.setPriority(rg.getPriority());
				ruleGroup.setRuleweight(rg.getRuleweight());
				ruleGroup.setSort(rg.getSort());
			}
			entity.setRuleGroups(ruleGroups);
			rules.add(entity);
        }
        // ruleEntry 引用规则名称
        Map<String,String> mapNames = new HashMap<String,String>();
		for(RuleEditEntity entity:rules) {
			RuleManage rm = entity.getRuleManage();
			List<RuleGroup> rgList = entity.getRuleGroups();
			if(rgList !=null && !rgList.isEmpty()) {
				RuleGroup rg = rgList.get(0);
				String name = mapNames.get(rg.getEntryId());
				if(StringUtils.isEmpty(name)) {
					mapNames.put(rg.getEntryId(), rm.getName());
				}else {
					mapNames.put(rg.getEntryId(), name+","+rm.getName());
				}
			}
		}

        //更改版本，重新保存RuleEntry,RuleGroupRef
        Map<String,String> old2newId = new HashMap<String,String>();//新旧id映射关系
        for(RuleEntry re:ruleEntryList) {
        	String oldId = re.getId();
        	re.setRuleNames(mapNames.get(oldId));
        	re.setVersion(newVersion);
        	re.preInsert();
        	old2newId.put(oldId,re.getId());
        	old2newId.put(re.getId(),oldId);
        }

        if (ruleEntryList != null && ruleEntryList.size() > 0) {
            RuleDataCollention<RuleEntry> ruleData = new RuleDataCollention<RuleEntry>();
            ruleData.setList(ruleEntryList);
            this.ruleEntryDao.insertBatch(ruleData);

            for(RuleEditEntity entity:rules) {
    			List<RuleGroup> rgList = entity.getRuleGroups();
    			if(rgList !=null && !rgList.isEmpty()) {
    	    		for(RuleGroup rg:rgList) {
    	    			rg.setEntryId(old2newId.get(rg.getEntryId()));
    	    		}
    			}
    		}

        }

        //更改版本，重新保存RuleGroupRef
        for (RuleGroupRef ruleGroupRef : ruleref) {
        	ruleGroupRef.setId(null);
        	ruleGroupRef.setVersion(newVersion);
        	ruleGroupRef.setEntryId(old2newId.get(ruleGroupRef.getEntryId()));//旧Id转换为新Id
		}
        this.ruleGroupRefService.insertBatch(ruleref);

        ComplexRuleGroup complexRuleGroup = new ComplexRuleGroup(ruleManage, ruleEntryList, rules);
        try {
        	Map<String, RuleReferenceData> refMap = new HashMap<String, RuleReferenceData>();
        	Map<String, RuleDataparams> funcparamMap = new HashMap<String, RuleDataparams>();

        	String drlContent =  ruleParseExpService.parseRuleGroupList(complexRuleGroup, refMap, funcparamMap, false, this);

    		//保存函数变量
            List<RuleDataparams> ruleParamdatas = new ArrayList<>(funcparamMap.values());
            this.ruleReferenceDataService.saveReferenceDataFuncRef(ruleParamdatas,ruleManage);
        	this.ruleReferenceDataService.saveReferenceData(refMap);

            RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
            ruleVersioninfo.init(ruleManage, drlContent);
            ruleVersioninfo.setProjectCode(ruleManage.getProjectCode());
            this.ruleVersioninfoService.save(ruleVersioninfo);
        }catch(Exception e) {
        	e.printStackTrace();
        	throw new BizException("",e.getMessage());
        }
//        //组织规则集，解析drl
//        RuleGroupVO ruleGroupVO = new RuleGroupVO(ruleManage,insertList,ruleEntryList);
//
//        RuleParseDrl ruleParseDrl = ruleDrlParseService.getParseObj(ruleManage.getProjectCode());
//        try {
//        	/**函数模式*/
//        	String context = null;
//        	if(isFuncModel) {
//        		context = ruleParseDrl.xml2RuleItemFunc(ruleGroupVO);
//        	}else {
//        		context = ruleParseDrl.xml2RuleItem(ruleGroupVO);
//        	}
//            List<RuleDataparams> ruleParamdatas = ruleParseDrl.getContainFuncParams();
//            ruleReferenceDataService.saveReferenceDataFuncRef(ruleParamdatas,ruleManage);
//            //收集引用数据
//            TestDataModeVO testDataModeVO = this.ruleDrlParseService.getDataMode(context, ruleManage.getProjectCode());
//            this.saveRuleRef(testDataModeVO, ruleManage);
//            RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
//            ruleVersioninfo.init(ruleManage, context);
//            this.ruleVersioninfoService.save(ruleVersioninfo);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BizException(e, "");
//        }
    }

    /**
     * 保存规则集没有改变版本，需保存drl,引用数据
     * @param manageId
     * @throws BizException
     */
    public void updateRuleGroupWithoutVersion(String manageId) throws BizException {
    	//保存ruleManage，主要是更新版本
        RuleManage ruleManage = this.ruleManageService.get(manageId);
        this.updateRuleGroupWithoutVersion(ruleManage);
    }
    /**
     * 保存规则集没有改变版本，需保存drl,引用数据
     * @param ruleManage 已查询出的完整ruleManage
     * @throws BizException
     */
    public void updateRuleGroupWithoutVersion(RuleManage ruleManage) throws BizException {
    	//更新部署drl
    	RuleVersioninfo arg0 = new RuleVersioninfo();
    	arg0.setManageId(ruleManage.getId());
    	arg0.setModelType(ruleManage.getModelType());
    	arg0.setModelCode(ruleManage.getCode());
    	arg0.setProjectCode(ruleManage.getProjectCode());
    	arg0.setVersion(ruleManage.getVersion());
    	List<RuleVersioninfo> rvList =  this.ruleVersioninfoService.findList(arg0);
    	if(rvList!=null&&rvList.size()>0) {
    		RuleVersioninfo ruleVersioninfo =  rvList.get(0);
            RuleEntry ruleEntry = new RuleEntry();
            ruleEntry.setManageId(ruleManage.getId());
            ruleEntry.setVersion(ruleManage.getVersion());
            List<RuleEntry> ruleEntryList = this.ruleEntryService.findList(ruleEntry);

            RuleGroup groupInfo = new RuleGroup();
            groupInfo.setManageId(ruleManage.getId());
            groupInfo.setVersion(ruleManage.getVersion());
            List<RuleGroup> insertList = this.ruleGroupRefService.findRuleGroupList(groupInfo);

            //组织规则集，解析drl
            RuleGroupVO ruleGroupVO = new RuleGroupVO(ruleManage,insertList,ruleEntryList);

            RuleParseDrl ruleParseDrl = ruleDrlParseService.getParseObj(ruleManage.getProjectCode());
            try {
            	/**函数模式*/
            	String context = null;
            	if(isFuncModel) {
            		context = ruleParseDrl.xml2RuleItemFunc(ruleGroupVO);
            	}else{
            		context = ruleParseDrl.xml2RuleItem(ruleGroupVO);
            	}

//                ruleVersioninfo.setRuleContent(context);
//                this.ruleVersioninfoService.save(ruleVersioninfo);

                //引用数据更新，版本不变，原有需要删除
                RuleReferenceData ruleReferenceData = new RuleReferenceData();
            	ruleReferenceData.setManageId(ruleManage.getId());
            	ruleReferenceData.setModelType(ruleManage.getModelType());
            	ruleReferenceData.setCode(ruleManage.getCode());
            	ruleReferenceData.setProjectCode(ruleManage.getProjectCode());
            	ruleReferenceData.setVersion(ruleManage.getVersion());
                ruleReferenceDataService.deleteByManage(ruleReferenceData);

				if("23".equals(ruleManage.getModelType())){
					// 复杂规则集
					updateRuleGroupNoVersion(ruleManage);
				}else{
					// 简单规则集
					simpleRuleGroupNoVersion(ruleManage);
				}

                //收集引用数据
//                List<RuleDataparams> ruleParamdatas = ruleParseDrl.getContainFuncParams();
//                ruleReferenceDataService.saveReferenceDataFuncRef(ruleParamdatas,ruleManage);
//
//                TestDataModeVO testDataModeVO = this.ruleDrlParseService.getDataMode(context, ruleManage.getProjectCode());
//                this.saveRuleRef(testDataModeVO, ruleManage);

            } catch (Exception e) {
                e.printStackTrace();
                throw new BizException(e, "");
            }
    	}else {
    		updateRuleGroup(ruleManage);
    	}
    }

	public void simpleRuleGroupNoVersion(RuleManage ruleManage) throws BizException {
		String oldVersion = ruleManage.getVersion();
		String manageId = ruleManage.getId();
		//简易规则集容器
		SimpleRuleGroup simpleRuleGroup = new SimpleRuleGroup();
		simpleRuleGroup.setRuleManage(ruleManage);

		//查询老版本规则
		RuleGroup ruleGroup = new RuleGroup();
		ruleGroup.setManageId(manageId);
		ruleGroup.setVersion(oldVersion);
		List<RuleGroup> ruleList = this.ruleGroupRefService.findRefRuleManage(ruleGroup);
		List<RuleEditEntity> rules = new ArrayList<>();
		for(RuleGroup rg:ruleList) {
			RuleManage rm = new RuleManage();
			rm.setId(rg.getManageId());
			rm.setName(rg.getRuleName());
			rm.setProjectCode(rg.getProjectCode());
			rm.setVersion(rg.getVersion());
			RuleEditEntity entity = new RuleEditEntity();
			entity.setRuleManage(rm);
			RuleGroup newRG = new RuleGroup();
			newRG.setManageId(rm.getId());
			newRG.setVersion(rm.getVersion());
			List<RuleGroup> ruleGroups = this.findList(newRG);
			entity.setRuleGroups(ruleGroups);
			rules.add(entity);
		}
		simpleRuleGroup.setRules(rules);

		try {
			this.saveOrUpdateRule(simpleRuleGroup);
		}catch(Exception e) {
			throw new BizException("",e.getMessage());
		}

	}
	/**
	 * 规则集不发布版本生成drl
	 * @param ruleManage 已查询出的完整ruleManage
	 * @throws BizException
	 */
	//TODO
	public void updateRuleGroupNoVersion(RuleManage ruleManage) throws BizException {
		//保存ruleManage，主要是更新版本
		String manageId = ruleManage.getId();
		String oldVersion = ruleManage.getVersion();
		//查询老版本RuleEntry
		RuleEntry ruleEntry = new RuleEntry();
		ruleEntry.setManageId(manageId);
		ruleEntry.setVersion(oldVersion);
		List<RuleEntry> ruleEntryList = this.ruleEntryService.findList(ruleEntry);

		//查询老版本RuleGroupRef关联关系
		RuleGroupRef refCon = new RuleGroupRef();
		refCon.setManageId(manageId);
		refCon.setVersion(oldVersion);
		List<RuleGroupRef> ruleref =  ruleGroupRefService.findList(refCon);

		//查询老版本规则
		String newVersion = ruleManage.getVersion();
		RuleGroup groupInfo = new RuleGroup();
		groupInfo.setManageId(manageId);
		groupInfo.setVersion(oldVersion);
		List<RuleGroup> ruleList = this.ruleGroupRefService.findRefRuleManage(groupInfo);
		List<RuleEditEntity> rules = new ArrayList<>();
		for(RuleGroup rg:ruleList) {
			RuleManage rm = new RuleManage();
			rm.setId(rg.getManageId());
			rm.setName(rg.getRuleName());
			rm.setProjectCode(rg.getProjectCode());
			rm.setVersion(rg.getVersion());
			RuleEditEntity entity = new RuleEditEntity();
			entity.setRuleManage(rm);
			RuleGroup newRG = new RuleGroup();
			newRG.setManageId(rm.getId());
			newRG.setVersion(rm.getVersion());
			List<RuleGroup> ruleGroups = this.findList(newRG);
			for(RuleGroup ruleGroup:ruleGroups) {
				ruleGroup.setRefId(rg.getRefId());
				ruleGroup.setEntryId(rg.getEntryId());
				ruleGroup.setPriority(rg.getPriority());
				ruleGroup.setRuleweight(rg.getRuleweight());
				ruleGroup.setSort(rg.getSort());
			}
			entity.setRuleGroups(ruleGroups);
			rules.add(entity);
		}
		ComplexRuleGroup complexRuleGroup = new ComplexRuleGroup(ruleManage, ruleEntryList, rules);
		try {
			Map<String, RuleReferenceData> refMap = new HashMap<String, RuleReferenceData>();
			Map<String, RuleDataparams> funcparamMap = new HashMap<String, RuleDataparams>();

			String drlContent =  ruleParseExpService.parseRuleGroupList(complexRuleGroup, refMap, funcparamMap, false, this);

			//保存函数变量
			List<RuleDataparams> ruleParamdatas = new ArrayList<>(funcparamMap.values());
			this.ruleReferenceDataService.saveReferenceDataFuncRef(ruleParamdatas,ruleManage);
			this.ruleReferenceDataService.saveReferenceData(refMap);

			RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
			ruleVersioninfo.init(ruleManage, drlContent);
			ruleVersioninfo.setProjectCode(ruleManage.getProjectCode());
			this.ruleVersioninfoService.save(ruleVersioninfo);
		}catch(Exception e) {
			e.printStackTrace();
			throw new BizException("",e.getMessage());
		}
	}
    /**
     * 根据ruleManage获取drl文本
     * @param ruleManage 其中ruleManage已经是查询出来的，不需要再次查询
     * @return
     */
    @Override
    public String getRuleDrl(RuleManage ruleManage) {
		RuleGroup ruleInfo = new RuleGroup();
		ruleInfo.setManageId(ruleManage.getId());
		ruleInfo.setVersion(ruleManage.getVersion());
		ruleInfo.setProjectCode(ruleManage.getProjectCode());
		List<RuleGroup> list = this.findList(ruleInfo);
		RuleSetVO ruleSetVO = new RuleSetVO();
		ruleSetVO.setRuleManage(ruleManage);
		ruleSetVO.setRules(list);

		RuleParseDrl ruleParseDrl = ruleDrlParseService.getParseObj(ruleManage.getProjectCode());
        String context = null;
		try {
			/** 函数模式 **/
			if(isFuncModel) {
				context = ruleParseDrl.xml2RuleItemForJava(ruleSetVO);
			}else {
				context = ruleParseDrl.xml2RuleItemNoWeight(ruleSetVO);
			}
		} catch (Exception e) {
			throw new BizException(e,"E-100004");
		}
        return context;
    }

    /**
     * 根据ruleManage获取drl文本
     * @param ruleManage
     * @return
     */
    public String getRuleDrl(RuleManage ruleManage,RuleGroup ruleInfo) {
		List<RuleGroup> list = new ArrayList<RuleGroup>();
		list.add(ruleInfo);
		RuleSetVO ruleSetVO = new RuleSetVO();
		ruleSetVO.setRuleManage(ruleManage);
		ruleSetVO.setRules(list);

		RuleParseDrl ruleParseDrl = ruleDrlParseService.getParseObj(ruleManage.getProjectCode());
        String context = null;
		try {
			/** 函数模式 **/
			if(isFuncModel) {
				context = ruleParseDrl.xml2RuleItemForJava(ruleSetVO);
			}else {
				context = ruleParseDrl.xml2RuleItemNoWeight(ruleSetVO);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
        return context;
    }

    @Override
    public String getRuleDrl(String projectCode,String code) {
    	RuleManage ruleManage = ruleManageService.findByCode(code, projectCode);
    	return getRuleDrl(ruleManage);
    }

    private void saveRuleRef(TestDataModeVO testDataModeVO, RuleManage ruleManage) throws BizException {
        List<TestDatasetVO> inputList = testDataModeVO.getInputDataModel();
        Map<String, RuleReferenceData> map = new HashMap<String, RuleReferenceData>();
        String key = null;
        for (TestDatasetVO datasetVO : inputList) {
            for (RuleItem testItem : datasetVO.getAttrList()) {
                key = testItem.getClassName() + "_" + testItem.getNameen() + "_" + ContentTypeEnum.in.code;
                testItem.setId(null);
                this.ruleReferenceDataService.collectCommonData(testItem, key, ContentTypeEnum.in.code, ruleManage, map);
            }
        }
        List<TestDatasetVO> thenList = testDataModeVO.getThenDataModel();
        for (TestDatasetVO thenDatasetVO : thenList) {
            for (RuleItem thenTestItem : thenDatasetVO.getAttrList()) {
                key = thenTestItem.getClassName() + "_" + thenTestItem.getNameen() + "_" + ContentTypeEnum.out.code;
                thenTestItem.setId(null);
                thenTestItem.setIsNewRecord(false);
                this.ruleReferenceDataService.collectCommonData(thenTestItem, key, ContentTypeEnum.out.code, ruleManage, map);
            }

        }
        this.ruleReferenceDataService.saveReferenceData(map);
    }

    @Override
    public String showRuleDrl(RuleSetVO ruleSetVO) throws Exception {
    	RuleParseDrl ruleParseDrl = ruleDrlParseService.getParseObj(ruleSetVO.getRuleManage().getProjectCode());
    	/**函数模式*/
    	String context = null;
    	if(isFuncModel) {
    		context = ruleParseDrl.xml2RuleItemForJava(ruleSetVO);
    	}else {
    		context = ruleParseDrl.xml2RuleItemNoWeight(ruleSetVO);
    	}
        return context;
    }

    @Override
    public String showRuleJava(RuleSetVO ruleSetVO) throws Exception {
		return null;
/*    	RuleManage ruleManage = ruleSetVO.getRuleManage();
    	ruleManage = ruleManageService.get(ruleManage);
    	ruleSetVO.setRuleManage(ruleManage);

        Map<String, Bom> indexBom = dataBomService.findBomMapByProjectCode(ruleManage.getProjectCode(),null);
        Map<String, Bom> handlerBom = BomCreator.findMapInOut(indexBom);
        Map<String, Domain> drlDomain = this.dataBomService.findDomainByProjectCode(ruleManage.getProjectCode());
        List<JFun> jfunList = ruleCodeblockService.genJFun(ruleManage.getProjectCode());
        Map<String,String> funcParamMap = ruleDataparamsService.getdataparams(ruleManage.getProjectCode());

        Map indexBomSC = ClassChangeUtils.<Bom, com.tansun.rule.sparkCode.entity.common.model.Bom>changeClass(indexBom);
        Map handlerBomSC = ClassChangeUtils.<Bom, com.tansun.rule.sparkCode.entity.common.model.Bom>changeClass(handlerBom);
        Map drlDomainSC = ClassChangeUtils.changeDomainClass(drlDomain);
        List jfunListSC = ClassChangeUtils.<JFun, com.tansun.rule.sparkCode.entity.common.jfun.JFun>changeClass(jfunList);

        RuleSetSC ruleSetSC = ClassChangeUtils.changeRuleSetVOClass(ruleSetVO);
    	return RuleGroupCreate.createCode(ruleSetSC, indexBomSC, handlerBomSC, drlDomainSC, jfunListSC, funcParamMap);*/

    }

    @Override
    public String showRuleJava(String manageId) throws Exception {
		return manageId;
/*    	RuleManage ruleManage = ruleManageService.get(manageId);

        RuleGroup ruleGroup = new RuleGroup();
        ruleGroup.setManageId(ruleManage.getId());
        ruleGroup.setVersion(ruleManage.getVersion());
        List<RuleGroup> ruleList = this.ruleGroupRefService.findRuleGroupList(ruleGroup);
        List<RuleGroupSC> ruleListSC = ClassChangeUtils.<RuleGroup, RuleGroupSC>changeClass(ruleList);

        Map<String, Bom> indexBom = dataBomService.findBomMapByProjectCode(ruleManage.getProjectCode(),null);
        Map<String, Bom> handlerBom = BomCreator.findMapInOut(indexBom);
        Map<String, Domain> drlDomain = this.dataBomService.findDomainByProjectCode(ruleManage.getProjectCode());
        List<JFun> jfunList = ruleCodeblockService.genJFun(ruleManage.getProjectCode());
        Map<String,String> funcParamMap = ruleDataparamsService.getdataparams(ruleManage.getProjectCode());

        Map indexBomSC = ClassChangeUtils.<Bom, com.tansun.rule.sparkCode.entity.common.model.Bom>changeClass(indexBom);
        Map handlerBomSC = ClassChangeUtils.<Bom, com.tansun.rule.sparkCode.entity.common.model.Bom>changeClass(handlerBom);
        Map drlDomainSC = ClassChangeUtils.changeDomainClass(drlDomain);
        List jfunListSC = ClassChangeUtils.<JFun, com.tansun.rule.sparkCode.entity.common.jfun.JFun>changeClass(jfunList);

        RuleManageSC ruleManageSC = ClassChangeUtils.<RuleManage,RuleManageSC>changeClass(ruleManage);

    	if( RuleModelTypeEnum.SimpleRuleGroup.code.equals(ruleManage.getModelType()) ) {
        	RuleSetSC ruleSetSC = new RuleSetSC();
        	ruleSetSC.setRuleManage(ruleManageSC);
	        ruleSetSC.setRules(ruleListSC);
	    	return RuleGroupCreate.createCode(ruleSetSC, indexBomSC, handlerBomSC, drlDomainSC, jfunListSC, funcParamMap);
    	}else {
            RuleEntry ruleEntry = new RuleEntry();
            ruleEntry.setManageId(ruleManage.getId());
            ruleEntry.setVersion(ruleManage.getVersion());
            List<RuleEntry> ruleEntryList = this.ruleEntryService.findList(ruleEntry);
            List<RuleEntrySC> ruleEntryListSC = ClassChangeUtils.<RuleEntry, RuleEntrySC>changeClass(ruleEntryList);

            //组织规则集，解析drl
            RuleGroupSCVO ruleGroupSCVO = new RuleGroupSCVO(ruleManageSC,ruleListSC,ruleEntryListSC);
    		return RuleGroupCreate.createCode(ruleGroupSCVO, indexBomSC, handlerBomSC, drlDomainSC, jfunListSC, funcParamMap);
    	}*/
    }

    @Override
    public void shiftSort(RuleManage ruleManage, String id1, String id2, String shiftType) throws BizException {
        RuleGroup ruleVo1 = this.get(id1);
        RuleGroup ruleVo2 = this.get(id2);
        this.ruleGroupRefService.shiftSort(ruleManage, id1, id2, shiftType);
//        Integer sal = ruleVo1 == null ? 0 : ruleVo1.getSort();
//        ruleVo1.setSort(ruleVo2.getSort());
//        ruleVo2.setSort(sal);
//        this.save(ruleVo1);
//        this.save(ruleVo2);
        //直接切换到最末不再交换，而是当前最小优先级减一
/*        if ("bot".equals(shiftType)) {
            sal = ruleManage.getCountSalience() - 1;
            ruleManage.setCountSalience(sal);
            ruleVo1.setSort(sal);
        } else if ("top".equals(shiftType)) {
            ruleVo1.setSort(ruleVo2.getSort() + 1);
//				ruleVo2.setSort(sal);
        } else {
            ruleVo1.setSort(ruleVo2.getSort());
            ruleVo2.setSort(sal);
        }
        this.save(ruleVo1);
        this.save(ruleVo2);
        */
    }

    /**
     * 规则集 编译
     */
    @Override
    public String compileDrl(String manageId) throws BizException {
        RuleManage ruleManage = this.ruleManageService.get(manageId);
        DroolsComplier complier = new DroolsComplier();

        RuleVersioninfo verInfo = new RuleVersioninfo();
        verInfo.setManageId(ruleManage.getId());
        verInfo.setVersion(ruleManage.getVersion());
        List<RuleVersioninfo> list = this.ruleVersioninfoService.findList(verInfo);

        if (list == null || list.size() == 0) {
            throw new BizException("当前规则集未保存，请先保存规则集，再进行编译！");
        }
        String context = list.get(0).getRuleContent();
        logger.debug(context);
        complier.addContent(context, ResourceType.DRL);

        complier.addContent(ruleCodeblockService.getEffectiveFunc(list.get(0).getProjectCode()), ResourceType.DRL);

//        verInfo.setProjectCode(list.get(0).getProjectCode());
//        verInfo.setManageId("func_" + list.get(0).getProjectCode());
//        verInfo.setVersion(null);
//        List<RuleVersioninfo> flist = this.ruleVersioninfoService.findList(verInfo);
//        if (flist != null && flist.size() > 0) {
//            try {
//                complier.addContent(flist.get(0).getRuleContent(), ResourceType.DRL);
//            } catch (Exception e) {
//                throw new BizException(e, "E-000000");
//            }
//        }
        String msg = complier.complie();
        return msg;
    }

    @Override
    public List<RuleGroup> generalRuleList(String projectCode) throws BizException {
        RuleManage ruleInfo = new RuleManage();
        ruleInfo.setProjectCode(projectCode);
        ruleInfo.setModelType(RuleModelTypeEnum.GeneralRule.code);
        ruleInfo.setStatus(Constant.RULE_STATUS_DEPLOY);
        List<RuleManage> list = this.ruleManageService.findList(ruleInfo);
        List<RuleGroup> results = new ArrayList<RuleGroup>();
        RuleGroup groupInfo = null;
        for (RuleManage ruleManage : list) {
            groupInfo = new RuleGroup();
            groupInfo.setManageId(ruleManage.getId());
            groupInfo.setVersion(ruleManage.getVersion());
            results.addAll(this.findList(groupInfo));
        }
        return results;
    }

    //获取全部的应用规则
    @SuppressWarnings("unchecked")
	@Override
    public List<RuleSetVO> generalRuleSetVOList(String projectCode) throws BizException {
    	String cacheKey = DataCache.getCacheKey(projectCode, DataCache.RULESETEFFECT_OPTION);
    	if(DataCache.canGetFromCache(cacheKey)) {
    		return (List<RuleSetVO>) DataCache.getValue(cacheKey);
    	}else {
    		RuleGroup ruleGroup = new RuleGroup();
        	ruleGroup.setProjectCode(projectCode);
            List<RuleGroup> list = this.findEffectRuleList(ruleGroup);

            //需要查询的的ManageId
            List<String> ids = new ArrayList<>();
            Map<String,List<RuleGroup>> id2Rules = new HashMap<>();
            for (RuleGroup rg : list) {
            	String manageId = rg.getManageId();
            	if(!ids.contains(manageId)) {
            		ids.add(manageId);
            	}
            	String key = manageId + rg.getVersion();
            	List<RuleGroup> rules = id2Rules.get(key);
            	if(rules == null) {
            		rules = new ArrayList<>();
            		id2Rules.put(key, rules);
            	}
            	rules.add(rg);
            }
			List<RuleManage> rmList = new ArrayList<>();
            if(ids!=null && ids.size()>0){
				 rmList = this.ruleManageService.findListByIds(ids);
			}
            List<RuleSetVO> results = new ArrayList<RuleSetVO>();
            for (RuleManage rm : rmList) {
            	String key = rm.getId()+rm.getVersion();
            	RuleSetVO ruleSetVO = new RuleSetVO();
            	ruleSetVO.setRuleManage(rm);
            	List<RuleGroup> rules = id2Rules.get(key);
            	ruleSetVO.setRules(rules);
                results.add(ruleSetVO);
            }
            DataCache.setValue(cacheKey, results);
            return results;
    	}
    }

    /**
     * 复杂规则集老版本保存为新版本，不包含脚本，仅包含版本信息
     * @param manageId
     * @param oldVersion
     * @param newVersion
     */
    public OldRuleGroupRefNew copyComplexRuleGroup(String manageId,String oldVersion,String newVersion) {
    	OldRuleGroupRefNew oldnew = new OldRuleGroupRefNew();
        //查询老版本RuleEntry
        RuleEntry ruleEntry = new RuleEntry();
        ruleEntry.setManageId(manageId);
        ruleEntry.setVersion(oldVersion);
        List<RuleEntry> ruleEntryList = this.ruleEntryService.findList(ruleEntry);

        //查询老版本RuleGroupRef关联关系
        RuleGroupRef refCon = new RuleGroupRef();
        refCon.setManageId(manageId);
        refCon.setVersion(oldVersion);
        List<RuleGroupRef> ruleref =  ruleGroupRefService.findList(refCon);

        //查询老版本规则
        RuleGroup groupInfo = new RuleGroup();
        groupInfo.setManageId(manageId);
        groupInfo.setVersion(oldVersion);
        List<RuleGroup> ruleList = this.ruleGroupRefService.findRefRuleManage(groupInfo);
        List<RuleEditEntity> rules = new ArrayList<>();
        for(RuleGroup rg:ruleList) {
        	RuleManage rm = new RuleManage();
        	rm.setId(rg.getManageId());
			rm.setName(rg.getRuleName());
			rm.setProjectCode(rg.getProjectCode());
			rm.setVersion(rg.getVersion());
			RuleEditEntity entity = new RuleEditEntity();
			entity.setRuleManage(rm);
			RuleGroup newRG = new RuleGroup();
			newRG.setManageId(rm.getId());
			newRG.setVersion(rm.getVersion());
			List<RuleGroup> ruleGroups = this.findList(newRG);
			for(RuleGroup ruleGroup:ruleGroups) {
				ruleGroup.setRefId(rg.getRefId());
				ruleGroup.setEntryId(rg.getEntryId());
				ruleGroup.setPriority(rg.getPriority());
				ruleGroup.setRuleweight(rg.getRuleweight());
				ruleGroup.setSort(rg.getSort());
			}
			entity.setRuleGroups(ruleGroups);
			rules.add(entity);
        }
        // ruleEntry 引用规则名称
        Map<String,String> mapNames = new HashMap<String,String>();
		for(RuleEditEntity entity:rules) {
			RuleManage rm = entity.getRuleManage();
			List<RuleGroup> rgList = entity.getRuleGroups();
			if(rgList !=null && !rgList.isEmpty()) {
				RuleGroup rg = rgList.get(0);
				String name = mapNames.get(rg.getEntryId());
				if(StringUtils.isEmpty(name)) {
					mapNames.put(rg.getEntryId(), rm.getName());
				}else {
					mapNames.put(rg.getEntryId(), name+","+rm.getName());
				}
			}
		}

        //更改版本，重新保存RuleEntry,RuleGroupRef
        Map<String,String> old2newId = new HashMap<String,String>();//新旧id映射关系
        for(RuleEntry re:ruleEntryList) {
        	String oldId = re.getId();
        	re.setRuleNames(mapNames.get(oldId));
        	re.setVersion(newVersion);
        	re.preInsert();
        	old2newId.put(oldId,re.getId());
        	old2newId.put(re.getId(),oldId);
        }

        if (ruleEntryList != null && ruleEntryList.size() > 0) {
            RuleDataCollention<RuleEntry> ruleData = new RuleDataCollention<RuleEntry>();
            ruleData.setList(ruleEntryList);
            this.ruleEntryDao.insertBatch(ruleData);

            for(RuleEditEntity entity:rules) {
    			List<RuleGroup> rgList = entity.getRuleGroups();
    			if(rgList !=null && !rgList.isEmpty()) {
    	    		for(RuleGroup rg:rgList) {
    	    			rg.setEntryId(old2newId.get(rg.getEntryId()));
    	    		}
    			}
    		}

        }

        //更改版本，重新保存RuleGroupRef
        Map<String,String> old2refnewId = new HashMap<String,String>();//新旧id映射关系
        for (RuleGroupRef ruleGroupRef : ruleref) {
        	String oldId = ruleGroupRef.getId();
        	ruleGroupRef.setId(null);
        	ruleGroupRef.preInsert();
        	ruleGroupRef.setVersion(newVersion);
        	ruleGroupRef.setEntryId(old2newId.get(ruleGroupRef.getEntryId()));//旧Id转换为新Id

        	old2refnewId.put(oldId,ruleGroupRef.getId());
        	old2refnewId.put(ruleGroupRef.getId(),oldId);
		}
        this.ruleGroupRefService.insertBatch(ruleref);
        oldnew.setOld2EntryNewId(old2newId);
        oldnew.setOld2RefNewId(old2refnewId);
        return oldnew;
    }
    /**
     * entry条目批量增加规则
     * @param ruleManage
     * @param fromGeneral
     * @param entryId
     */
	public RuleGroupRef addEntryGroup(RuleManage ruleManage,String[] fromGeneral, String entryId) {
        String oldVersion = ruleManage.getVersion();
        Integer countSalience = ruleManage.getCountSalience();
        if(countSalience==null)countSalience = 999999;
        List<RuleGroupRef> ruleGroupRefs = new ArrayList<RuleGroupRef>();
        if(!oldVersion.contains("_modify")) {
        	ruleManage.setStatus(Constant.RULE_STATUS_NORMAL);
        	ruleManage.initVersion(ruleManage.getIsTemp());
            ruleManage.setVersion(ruleManage.getVersion()+"_modify");

            Map<String,String> old2newId = copyComplexRuleGroup(ruleManage.getId(), oldVersion, ruleManage.getVersion()).getOld2EntryNewId();

            entryId = old2newId.get(entryId);

            RuleGroupRef refCon = new RuleGroupRef();
            refCon.setManageId(ruleManage.getId());
            refCon.setVersion(oldVersion);
            refCon.setEntryId(entryId);
            ruleGroupRefs =  ruleGroupRefService.findList(refCon);

            for(RuleGroupRef ref:ruleGroupRefs) {
            	ref.setId(null);
            	ref.setVersion(ruleManage.getVersion());
            }
        }
        RuleEntry ruleEntry = this.ruleEntryService.get(entryId);

        //引用规则时， 新增规则与规则集的引用关系
        List<RuleManage> rmList = this.ruleManageService.findListByIds(Arrays.asList(fromGeneral));//查找引用规则
        String ruleNames = "";
        for (RuleManage rm: rmList) {
        	countSalience = countSalience-1;
        	String ruleManageId = rm.getId();//规则的manageId
        	RuleGroupRef ref = new RuleGroupRef();
        	ref.setRuleId(ruleManageId);
        	ref.setManageId(ruleManage.getId());
        	ref.setVersion(ruleManage.getVersion());
        	ref.setProjectCode(ruleManage.getProjectCode());
        	ref.setSort(countSalience);
        	ref.setEntryId(entryId);
        	ruleGroupRefs.add(ref);
        	ruleNames += ","+rm.getName();
        }
    	this.ruleGroupRefService.insertBatch(ruleGroupRefs);

    	if(StringUtils.isEmpty(ruleEntry.getRuleNames())) {
    		if(StringUtils.isEmpty(ruleEntry.getRuleNames())) {
    			ruleEntry.setRuleNames(ruleNames);
    		}else {
    			ruleEntry.setRuleNames(ruleNames.substring(1));
    		}
    	}else{
    		ruleEntry.setRuleNames(ruleEntry.getRuleNames()+ruleNames);
    	}
    	this.ruleEntryService.saveOrUpdate(ruleEntry);

        ruleManage.setCountSalience(countSalience);
        if (ruleManage.getCreateDate() == null) {
        	ruleManage.setCreateDate(new Date());
        }
        if (ruleManage.getUpdateDate() == null) {
        	ruleManage.setUpdateDate(new Date());
        }
        this.ruleManageService.save(ruleManage);

		RuleGroupRef rf = new RuleGroupRef();
        rf.setVersion(ruleManage.getVersion());
        rf.setEntryId(entryId);
        return rf;
	}

	/**
	 * 批量添加规则到简易规则集
	 * @param ruleManage 已经查询出来了
	 * @param fromGeneral
	 */
	public RuleGroupRef addSimpleGroup(RuleManage ruleManage,String[] fromGeneral) {
    	//保存ruleManage，主要是更新版本
        String oldVersion = ruleManage.getVersion();
        Integer countSalience = ruleManage.getCountSalience();
        if(countSalience==null)countSalience = 999999;
        ruleManage.setStatus(Constant.RULE_STATUS_NORMAL);

        List<RuleGroupRef> ruleGroupRefs = new ArrayList<RuleGroupRef>();
        if(!oldVersion.contains("_modify")) {
        	ruleManage.setStatus(Constant.RULE_STATUS_NORMAL);
        	ruleManage.initVersion(ruleManage.getIsTemp());
            ruleManage.setVersion(ruleManage.getVersion()+"_modify");

            RuleGroupRef refCon = new RuleGroupRef();
            refCon.setManageId(ruleManage.getId());
            refCon.setVersion(oldVersion);
            ruleGroupRefs =  ruleGroupRefService.findList(refCon);

            for(RuleGroupRef ref:ruleGroupRefs) {
            	ref.setId(null);
            	ref.setVersion(ruleManage.getVersion());
            }

        }

        //引用规则时， 新增规则与规则集的引用关系
        List<RuleManage> rmList = this.ruleManageService.findListByIds(Arrays.asList(fromGeneral));
        for(RuleManage rm:rmList) {
        	countSalience = countSalience-1;
        	String ruleManageId = rm.getId();//规则的manageId
        	RuleGroupRef ref = new RuleGroupRef();
        	ref.setRuleId(ruleManageId);
        	ref.setManageId(ruleManage.getId());
        	ref.setVersion(ruleManage.getVersion());
        	ref.setProjectCode(ruleManage.getProjectCode());
        	ref.setSort(countSalience);
        	ruleGroupRefs.add(ref);
        }

//        Map<String,Object> map = new HashMap<String,Object>();
//        map.put("ids", fromGeneral);
//        List<RuleGroup> rgList = this.dao.findListByIds(map);//查找引用规则
//        for (RuleGroup rg: rgList) {
//        	countSalience = countSalience-1;
//        	String ruleManageId = rg.getManageId();//规则的manageId
//        	RuleGroupRef ref = new RuleGroupRef();
//        	ref.setRuleId(ruleManageId);
//        	ref.setManageId(ruleManage.getId());
//        	ref.setVersion(ruleManage.getVersion());
//        	ref.setProjectCode(ruleManage.getProjectCode());
//        	ref.setSort(countSalience);
//        	ruleGroupRefs.add(ref);
//        }
    	this.ruleGroupRefService.insertBatch(ruleGroupRefs);

        ruleManage.setCountSalience(countSalience);
        if (ruleManage.getCreateDate() == null) {
        	ruleManage.setCreateDate(new Date());
        }
        if (ruleManage.getUpdateDate() == null) {
        	ruleManage.setUpdateDate(new Date());
        }
        this.ruleManageService.save(ruleManage);

		RuleGroupRef rf = new RuleGroupRef();
        rf.setVersion(ruleManage.getVersion());
        return rf;
	}

    @Override
    public RuleGroupRef addGroupRuleFromGerneal(String[] fromGeneral, String manageId,String entryId) throws BizException {
        RuleManage ruleManage = this.ruleManageService.get(manageId);
        RuleGroupRef returnData = null;
        if( RuleModelTypeEnum.PolicyRuleGroup.code.equals(ruleManage.getModelType()) ){
        	returnData = this.addEntryGroup(ruleManage, fromGeneral, entryId);
        }else {
        	returnData = this.addSimpleGroup(ruleManage,fromGeneral);
        }
        return returnData;
    }

    @Override
    public void updateGeneralRuleVersion(RuleManage ruleManage) throws BizException {
    	RuleGroup ruleGroupInfo = new RuleGroup();
        if (ruleManage.getOldId() != null) {
            ruleGroupInfo.setManageId(ruleManage.getOldId());
        } else {
            ruleGroupInfo.setManageId(ruleManage.getId());

        }
        ruleGroupInfo.setVersion(ruleManage.getOldVersion());
        List<RuleGroup> list = this.findList(ruleGroupInfo);
        if (list != null && list.size() > 0) {
        	RuleGroup ruleGroup = list.get(0);
    		ruleGroup.setId(null);
    		ruleGroup.setManageId(ruleManage.getId());
    		ruleGroup.setVersion(ruleManage.getVersion());
            this.save(ruleGroup);

//            /**drl保存在ruleversioninfo**/
//            String ruleDrl = getRuleDrl(ruleManage,ruleGroup);
//            RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
//            ruleVersioninfo.init(ruleManage, ruleDrl);
//            this.ruleVersioninfoService.save(ruleVersioninfo);

			RuleReferenceData referenceData = new RuleReferenceData();
			if (ruleManage.getOldId() != null) {
			    referenceData.setManageId(ruleManage.getOldId());
			} else {
			    referenceData.setManageId(ruleManage.getId());
			}
			referenceData.setVersion(ruleManage.getOldVersion());
			List<RuleReferenceData> refList = this.ruleReferenceDataService.findList(referenceData);
			this.ruleReferenceDataService.insertBatch(refList, new String[]{"id","manageId", "version"}, new Object[]{null, ruleManage.getId(),ruleManage.getVersion()}, true);
      }
    }

    public void updateSimpleRuleGroupVersion(RuleManage ruleManage) throws BizException {
        RuleGroupRef refCon = new RuleGroupRef();
        if (ruleManage.getOldId() != null) {
            refCon.setManageId(ruleManage.getOldId());
        } else {
        	refCon.setManageId(ruleManage.getId());
        }
        refCon.setVersion(ruleManage.getOldVersion());
        refCon.setProjectCode(ruleManage.getProjectCode());
        //查询关联表,获取关联信息
        List<RuleGroupRef> ruleref =  ruleGroupRefService.findList(refCon);

        if(ruleref != null && ruleref.size() > 0) {
            //更改版本，重新保存RuleGroupRef
            for (RuleGroupRef ruleGroupRef : ruleref) {
            	ruleGroupRef.setId(null);
            	ruleGroupRef.setVersion(ruleManage.getVersion());
    		}
            this.ruleGroupRefService.insertBatch(ruleref);

			RuleReferenceData referenceData = new RuleReferenceData();
			if (ruleManage.getOldId() != null) {
			    referenceData.setManageId(ruleManage.getOldId());
			} else {
			    referenceData.setManageId(ruleManage.getId());
			}
			referenceData.setVersion(ruleManage.getOldVersion());
			List<RuleReferenceData> refList = this.ruleReferenceDataService.findList(referenceData);
			this.ruleReferenceDataService.insertBatch(refList, new String[]{"id","manageId", "version"}, new Object[]{null, ruleManage.getId(),ruleManage.getVersion()}, true);
      }
    }

    /**
     * 版本切换时调用,主要操作增加一个新的版本
     * ruleManage已更新 旧id及旧version存放
     */
    @Override
    public void updateVersion(RuleManage ruleManage) throws BizException {
    	if(RuleModelTypeEnum.GeneralRule.code.equals(ruleManage.getModelType())) {
    		updateGeneralRuleVersion(ruleManage);
    		return;
    	}else if(RuleModelTypeEnum.SimpleRuleGroup.code.equals(ruleManage.getModelType())) {
    		updateSimpleRuleGroupVersion(ruleManage);
    		return;
    	}
        RuleGroup ruleGroupInfo = new RuleGroup();
        RuleEntry ruleEntry = new RuleEntry();
        RuleGroupRef refCon = new RuleGroupRef();
        if (ruleManage.getOldId() != null) {
            ruleGroupInfo.setManageId(ruleManage.getOldId());
            ruleEntry.setManageId(ruleManage.getOldId());
            refCon.setManageId(ruleManage.getOldId());
        } else {
        	refCon.setManageId(ruleManage.getId());
            ruleEntry.setManageId(ruleManage.getId());
            ruleGroupInfo.setManageId(ruleManage.getId());
        }

        ruleGroupInfo.setVersion(ruleManage.getOldVersion());
        refCon.setVersion(ruleManage.getOldVersion());
        ruleEntry.setVersion(ruleManage.getOldVersion());

        ruleGroupInfo.setProjectCode(ruleManage.getProjectCode());
        refCon.setProjectCode(ruleManage.getProjectCode());
        ruleEntry.setProjectCode(ruleManage.getProjectCode());

        //查询条目表
        List<RuleEntry> ruleEntryList = ruleEntryService.findList(ruleEntry);

        //查询关联表,获取关联信息
        List<RuleGroupRef> ruleref =  ruleGroupRefService.findList(refCon);
        //分组
        Map<String,List<RuleGroupRef>> refmap = new HashMap<String,List<RuleGroupRef>>();
        if(ruleref != null && ruleref.size() > 0) {
        	 for (RuleGroupRef ruleGroupRef : ruleref) {
        		 List<RuleGroupRef> group = null;
             	String key = ruleGroupRef.getEntryId();
        		if(refmap.containsKey(key)) {
        			group = refmap.get(key);
        		}else {
        			group = new ArrayList<RuleGroupRef>();
        			refmap.put(key, group);
        		}
        		group.add(ruleGroupRef);
     		}
        	RuleReferenceData referenceData = new RuleReferenceData();
        	if (ruleManage.getOldId() != null) {
        		referenceData.setManageId(ruleManage.getOldId());
        	} else {
        		referenceData.setManageId(ruleManage.getId());
        	}
        	referenceData.setVersion(ruleManage.getOldVersion());
        	List<RuleReferenceData> refList = this.ruleReferenceDataService.findList(referenceData);
        	this.ruleReferenceDataService.insertBatch(refList, new String[]{"id","manageId","code", "version"}, new Object[]{null, ruleManage.getId(),ruleManage.getCode(),ruleManage.getVersion()}, true);
        }
        //复制关联关系
        if(ruleEntryList != null && ruleEntryList.size() > 0) {
        	List<RuleGroupRef> allList = new ArrayList<RuleGroupRef>();
        	//更改版本，重新保存RuleEntry,RuleGroupRef
            Map<String,String> old2newId = new HashMap<String,String>();//新旧id映射关系
            for(RuleEntry re:ruleEntryList) {
            	String oldId = re.getId();
    			//条目复制
    			re.setId(null);
    			re.setManageId(ruleManage.getId());
    			re.setProjectCode(ruleManage.getProjectCode());
    			re.setVersion(ruleManage.getVersion());
            	re.preInsert();
            	old2newId.put(oldId,re.getId());
            	old2newId.put(re.getId(),oldId);
            }
            RuleDataCollention<RuleEntry> ruleData = new RuleDataCollention<RuleEntry>();
            ruleData.setList(ruleEntryList);
            this.ruleEntryDao.insertBatch(ruleData);

    		for(RuleEntry re:ruleEntryList) {
    			String entryId = old2newId.get(re.getId());
    			//关联数据复制
    			List<RuleGroupRef> rgrList = refmap.get(entryId);
    			if (rgrList != null && rgrList.size() > 0) {
                    for (RuleGroupRef ruleGroupRef : rgrList) {
                    	ruleGroupRef.setId(null);
                    	ruleGroupRef.setVersion(ruleManage.getVersion());
                    	ruleGroupRef.setEntryId(re.getId());
                    	ruleGroupRef.setManageId(ruleManage.getId());
                    	ruleGroupRef.setProjectCode(ruleManage.getProjectCode());
            		}
                    allList.addAll(rgrList);
                }
        	}
    		this.ruleGroupRefService.insertBatch(allList);

        }
//        RuleGroup groupInfo = new RuleGroup();
//        groupInfo.setManageId(ruleManage.getId());
//        groupInfo.setVersion(ruleManage.getVersion());
//        List<RuleGroup> insertList = this.ruleGroupRefService.findRuleGroupList(groupInfo);
//
//        //组织规则集，解析drl
//        RuleGroupVO ruleGroupVO = new RuleGroupVO(ruleManage,insertList,ruleEntryList);
//
//        RuleParseDrl ruleParseDrl = ruleDrlParseService.getParseObj(ruleManage.getProjectCode());
//        try {
//        	/**函数模式*/
//        	String context = null;
//        	if(isFuncModel) {
//        		context = ruleParseDrl.xml2RuleItemFunc(ruleGroupVO);
//        	}else{
//        		context = ruleParseDrl.xml2RuleItem(ruleGroupVO);
//        	}
//        	RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
//        	ruleVersioninfo.setManageId(ruleManage.getId());
//        	ruleVersioninfo.setModelType(ruleManage.getModelType());
//        	ruleVersioninfo.setModelCode(ruleManage.getCode());
//        	ruleVersioninfo.setProjectCode(ruleManage.getProjectCode());
//        	ruleVersioninfo.setVersion(ruleManage.getVersion());
//            ruleVersioninfo.setRuleContent(context);
//            this.ruleVersioninfoService.save(ruleVersioninfo);
//        }catch(Exception e){
//            e.printStackTrace();
//            throw new BizException(e, "");
//        }
//        List<RuleGroup> list = this.findList(ruleGroupInfo);
//        if (list != null && list.size() > 0) {
//            for (RuleGroup ruleGroup : list) {
//                ruleGroup.setId(null);
//                ruleGroup.setManageId(ruleManage.getId());
//                ruleGroup.setVersion(ruleManage.getVersion());
//                this.save(ruleGroup);
//            }
//            RuleReferenceData referenceData = new RuleReferenceData();
//            if (ruleManage.getOldId() != null) {
//                referenceData.setManageId(ruleManage.getOldId());
//            } else
//                referenceData.setManageId(ruleManage.getId());
//            referenceData.setVersion(ruleManage.getOldVersion());
//            List<RuleReferenceData> refList = this.ruleReferenceDataService.findList(referenceData);
//            this.ruleReferenceDataService.insertBatch(refList, new String[]{"id","manageId", "version"}, new Object[]{null, ruleManage.getId(),ruleManage.getVersion()}, true);
//        }

    }

    @Override
    public void copyRule(RuleManage oldRuleManage, RuleManage ruleManage) throws BizException {
		ruleManage.setOldVersion(oldRuleManage.getVersion());
		ruleManage.setOldId(oldRuleManage.getId());
		ruleManage.setProjectCode(oldRuleManage.getProjectCode());
		ruleManage.setCountSalience(oldRuleManage.getCountSalience());
        this.updateVersion(ruleManage);

    }
    /**
     * 获取去全部关联关系
     * @param projectCode
     * @param ruleManageId
     * @return
     */
    @SuppressWarnings("unchecked")
	public List<RuleRefVO> findRuleRefVOList(String projectCode,String ruleManageId){
    	List<RuleRefVO> allRef = null;
    	Map<String,List<RuleRefVO>> allRefMap = null;
    	String cacheKey = DataCache.getCacheKey(projectCode, DataCache.RULE_REF_ENTRY_GROUP_OPTION);
    	if(DataCache.canGetFromCache(cacheKey)) {
    		allRefMap = (Map<String, List<RuleRefVO>>) DataCache.getValue(cacheKey);
    	}else {
    		allRefMap = new ConcurrentHashMap<String,List<RuleRefVO>>();
            DataCache.setValue(cacheKey, allRefMap);
    	}
    	if(allRefMap.containsKey(ruleManageId)) {
    		allRef = allRefMap.get(ruleManageId);
    	}else {
    		RuleGroupRef ruleGroupRef = new RuleGroupRef();
        	ruleGroupRef.setRuleId(ruleManageId);//根据manageId查找
            List<RuleGroupRef> groupRefList = ruleGroupRefService.findList(ruleGroupRef);

            //收集id
            Set<String> manageIdSet = new HashSet<String>();
            List<String> entryIdList = new ArrayList<String>();
            for(RuleGroupRef groupRef:groupRefList) {
            	String manageId = groupRef.getManageId();
            	String entryId = groupRef.getEntryId();
            	manageIdSet.add(manageId);
            	entryIdList.add(entryId);
            }

            List<RuleManage> manageList = this.ruleManageService.findListByIds(new ArrayList<String>(manageIdSet));
            Map<String,RuleManage> manageId2Name = new HashMap<String,RuleManage>();
            for(RuleManage rm :manageList) {
            	manageId2Name.put(rm.getId(), rm);
            }
            List<RuleEntry> entryList = this.ruleEntryService.findListByIds(entryIdList);
            Map<String,RuleEntry> entryId2RuleEntry = new HashMap<String,RuleEntry>();
            for(RuleEntry entry :entryList) {
            	entryId2RuleEntry.put(entry.getId(), entry);
            }

            Map<String,RuleRefVO> manageId2RuleRefVO = new HashMap<String,RuleRefVO>();
            for(RuleGroupRef groupRef:groupRefList) {
            	String manageId = groupRef.getManageId();
            	String entryId = groupRef.getEntryId();
            	RuleRefVO ruleRef = null;
            	if(manageId2RuleRefVO.containsKey(manageId)) {
            		ruleRef = manageId2RuleRefVO.get(manageId);
            	}else {
            		ruleRef = new RuleRefVO();
            		RuleManage rm = manageId2Name.get(manageId);
            		ruleRef.setRuleGroupName(rm.getName());
            		ruleRef.setRankRelationId(rm.getRankRelationId());
            		manageId2RuleRefVO.put(manageId, ruleRef);
            	}
            	RuleEntry ruleEntry = entryId2RuleEntry.get(entryId);
            	if(ruleEntry!=null) {
	            	String entryName = ruleEntry.getEntryName();
	            	ruleRef.addEntryNames(entryName);
            	}
            }

            allRef = new ArrayList<RuleRefVO>(manageId2RuleRefVO.values());
            allRefMap.put(ruleManageId, allRef);
    	}
    	return allRef;
    }

    @Override
    public RuleRefVOPage findRuleReference(RuleRefVOPage ruleRefVOPage) {
    	String ruleGroupName = ruleRefVOPage.getRuleGroupName();
    	String entryName = ruleRefVOPage.getRuleEntryName();
    	String rankRelationId = (String) ruleRefVOPage.getDataMap().get("rankRelationId");
    	List<String> ids = ruleProjectRankService.findIdsByRecursion(rankRelationId,"policyRuleGroup");

    	List<RuleRefVO> allRef = findRuleRefVOList(ruleRefVOPage.getProjectCode(),ruleRefVOPage.getId());

    	List<RuleRefVO> needRef = new ArrayList<RuleRefVO>();
    	if(StringUtils.isEmpty(ruleGroupName)&&StringUtils.isEmpty(entryName)) {
    		if(isFilter) {
	    		for(RuleRefVO ruleVO:allRef) {
	        		if( ids.contains(ruleVO.getRankRelationId())) {
	    				needRef.add(ruleVO);
	        		}
	        	}
    		}else {
    			needRef = allRef;
    		}
    	}else if(StringUtils.isNotEmpty(ruleGroupName)&&StringUtils.isEmpty(entryName)) {
    		if(isFilter) {
	    		for(RuleRefVO ruleVO:allRef) {
	        		if( ids.contains(ruleVO.getRankRelationId()) && ruleGroupName.equals(ruleVO.getRuleGroupName()) ) {
	    				needRef.add(ruleVO);
	        		}
	        	}
    		}else {
	    		for(RuleRefVO ruleVO:allRef) {
	        		if( ruleGroupName.equals(ruleVO.getRuleGroupName()) ) {
	    				needRef.add(ruleVO);
	        		}
	        	}
    		}
    	}else if(StringUtils.isNotEmpty(ruleGroupName)&&StringUtils.isNotEmpty(entryName)) {
    		if(isFilter) {
        		for(RuleRefVO ruleVO:allRef) {
            		if( ids.contains(ruleVO.getRankRelationId()) && ruleGroupName.equals(ruleVO.getRuleGroupName()) && ruleVO.getEntryNames().contains(entryName)) {
            			RuleRefVO newVo= new RuleRefVO();
            			newVo.setRuleGroupName(ruleVO.getRuleGroupName());
            			newVo.setEntryNames(Arrays.asList(entryName));
        				needRef.add(newVo);
            		}
            	}
    		}else {
        		for(RuleRefVO ruleVO:allRef) {
            		if( ruleGroupName.equals(ruleVO.getRuleGroupName()) && ruleVO.getEntryNames().contains(entryName)) {
            			RuleRefVO newVo= new RuleRefVO();
            			newVo.setRuleGroupName(ruleVO.getRuleGroupName());
            			newVo.setEntryNames(Arrays.asList(entryName));
        				needRef.add(newVo);
            		}
            	}
    		}
    	}else {
    		if(isFilter) {
        		for(RuleRefVO ruleVO:allRef) {
            		if( ids.contains(ruleVO.getRankRelationId()) && ruleVO.getEntryNames().contains(entryName)) {
            			RuleRefVO newVo= new RuleRefVO();
            			newVo.setRuleGroupName(ruleVO.getRuleGroupName());
            			newVo.setEntryNames(Arrays.asList(entryName));
        				needRef.add(newVo);
            		}
            	}
    		}else {
        		for(RuleRefVO ruleVO:allRef) {
            		if( ruleVO.getEntryNames().contains(entryName)) {
            			RuleRefVO newVo= new RuleRefVO();
            			newVo.setRuleGroupName(ruleVO.getRuleGroupName());
            			newVo.setEntryNames(Arrays.asList(entryName));
        				needRef.add(newVo);
            		}
            	}
    		}

    	}
    	RuleRefVOPage page = new RuleRefVOPage(ruleRefVOPage,needRef);
		return page;
    }


    @Override
	public void copyRuleGroup(ProjectInfo projectInfo) throws Exception {
    	// 查询出ruleManage
    	RuleManage ruleManage = this.ruleManageService.get(projectInfo.getManageId());

    	RuleManage newRuleManage = (RuleManage)BeanUtils.cloneBean(ruleManage);
    	// ruleManage 名称替换 ，日期替换 ，id置空
    	Date date = new Date();
    	newRuleManage.setId(null);
    	// 名称添加随机id防止重复
    	newRuleManage.setName(ruleManage.getName()+"_Copy"+StringUtils.generateShortUuid());
    	newRuleManage.setCreateDate(date);
    	newRuleManage.setUpdateDate(date);
    	newRuleManage.setCode(null);
    	newRuleManage.setVersion(null);
    	newRuleManage.setActiveVersion(null);
    	this.ruleManageService.saveOrUpdate(newRuleManage);

		//新增第一个规则的时候初始化内置变量
		dataModelService.saveOrUpdateBuiltinParam(newRuleManage.getCode(),newRuleManage.getName(), newRuleManage.getModelType(), newRuleManage.getProjectCode(), newRuleManage.getCreateBy());
    	// 复杂规则集
    	if(RuleModelTypeEnum.PolicyRuleGroup.code.equals(ruleManage.getModelType())) {
            RuleEntry ruleEntry = new RuleEntry();
            ruleEntry.setVersion(ruleManage.getVersion());
            ruleEntry.setProjectCode(ruleManage.getProjectCode());
            ruleEntry.setManageId(ruleManage.getId());

            RuleGroupRef refCon = new RuleGroupRef();
            refCon.setVersion(ruleManage.getVersion());
            refCon.setProjectCode(ruleManage.getProjectCode());
            refCon.setManageId(ruleManage.getId());

            //查询条目表
            List<RuleEntry> ruleEntryList = ruleEntryService.findList(ruleEntry);
            //查询关联表,获取关联信息
            List<RuleGroupRef> ruleref =  ruleGroupRefService.findList(refCon);
            //分组
            Map<String,List<RuleGroupRef>> refmap = new HashMap<String,List<RuleGroupRef>>();
            if(ruleref != null && ruleref.size() > 0) {
            	 for (RuleGroupRef ruleGroupRef : ruleref) {
            		 List<RuleGroupRef> group = null;
                 	String key = ruleGroupRef.getEntryId();
            		if(refmap.containsKey(key)) {
            			group = refmap.get(key);
            		}else {
            			group = new ArrayList<RuleGroupRef>();
            			refmap.put(key, group);
            		}
            		group.add(ruleGroupRef);
         		}
            }
            //复制关联关系
            if(ruleEntryList != null && ruleEntryList.size() > 0) {
            	List<RuleGroupRef> allList = new ArrayList<RuleGroupRef>();
            	//更改版本，重新保存RuleEntry,RuleGroupRef
                Map<String,String> old2newId = new HashMap<String,String>();//新旧id映射关系
                for(RuleEntry re:ruleEntryList) {
                	String oldId = re.getId();
        			//条目复制
        			re.setId(null);
        			re.setManageId(newRuleManage.getId());
        			re.setProjectCode(newRuleManage.getProjectCode());
        			re.setVersion(newRuleManage.getVersion());
                	re.preInsert();
                	old2newId.put(oldId,re.getId());
                	old2newId.put(re.getId(),oldId);
                }
                RuleDataCollention<RuleEntry> ruleData = new RuleDataCollention<RuleEntry>();
                ruleData.setList(ruleEntryList);
                this.ruleEntryDao.insertBatch(ruleData);

        		for(RuleEntry re:ruleEntryList) {
        			String entryId = old2newId.get(re.getId());
        			//关联数据复制
        			List<RuleGroupRef> rgrList = refmap.get(entryId);
        			if (rgrList != null && rgrList.size() > 0) {
                        for (RuleGroupRef ruleGroupRef : rgrList) {
                        	ruleGroupRef.setId(null);
                        	ruleGroupRef.setVersion(newRuleManage.getVersion());
                        	ruleGroupRef.setEntryId(re.getId());
                        	ruleGroupRef.setManageId(newRuleManage.getId());
                        	ruleGroupRef.setProjectCode(newRuleManage.getProjectCode());
                		}
                        allList.addAll(rgrList);
                    }
            	}
        		this.ruleGroupRefService.insertBatch(allList);
            }

            //查询老版本规则
            RuleGroup ruleGroup = new RuleGroup();
            ruleGroup.setManageId(newRuleManage.getId());
            ruleGroup.setVersion(newRuleManage.getVersion());
            List<RuleGroup> ruleList = this.ruleGroupRefService.findRefRuleManage(ruleGroup);
            List<RuleEditEntity> rules = new ArrayList<>();
            for(RuleGroup rg:ruleList) {
            	RuleManage rm = new RuleManage();
            	rm.setId(rg.getManageId());
    			rm.setName(rg.getRuleName());
    			rm.setProjectCode(rg.getProjectCode());
    			rm.setVersion(rg.getVersion());

    			RuleGroup newRG = new RuleGroup();
    			newRG.setManageId(rm.getId());
    			newRG.setVersion(rm.getVersion());
    			List<RuleGroup> ruleGroups = this.findList(newRG);
    			for(RuleGroup each:ruleGroups) {
    				each.setRefId(rg.getRefId());
    				each.setEntryId(rg.getEntryId());
    				each.setPriority(rg.getPriority());
    				each.setRuleweight(rg.getRuleweight());
    				each.setSort(rg.getSort());
    			}
    			RuleEditEntity entity = new RuleEditEntity();
    			entity.setRuleManage(rm);
    			entity.setRuleGroups(ruleGroups);
    			rules.add(entity);
            }


            ComplexRuleGroup complexRuleGroup = new ComplexRuleGroup(newRuleManage, ruleEntryList, rules);
            try {
            	Map<String, RuleReferenceData> refMap = new HashMap<String, RuleReferenceData>();
            	Map<String, RuleDataparams> funcparamMap = new HashMap<String, RuleDataparams>();

            	String drlContent =  ruleParseExpService.parseRuleGroupList(complexRuleGroup, refMap, funcparamMap, false, this);
            	this.ruleReferenceDataService.saveReferenceData(refMap);
        		//保存函数变量
                List<RuleDataparams> ruleParamdatas = new ArrayList<>(funcparamMap.values());
                this.ruleReferenceDataService.saveReferenceDataFuncRef(ruleParamdatas,ruleManage);
                RuleVersioninfo ruleVersioninfo = new RuleVersioninfo();
                ruleVersioninfo.init(newRuleManage, drlContent);
                ruleVersioninfo.setProjectCode(ruleManage.getProjectCode());
                this.ruleVersioninfoService.save(ruleVersioninfo);
            }catch(Exception e) {
            	e.printStackTrace();
            	throw new BizException("",e.getMessage());
            }
    	}else {
        	// 简易规则集主要复制，ruleManage与ruleGroupRefList
        	RuleGroupRef condition = new RuleGroupRef();
        	condition.setManageId(ruleManage.getId());
        	condition.setVersion(ruleManage.getVersion());
        	// 关联关系
        	List<RuleGroupRef> ruleGroupRefList = this.ruleGroupRefService.findList(condition);

        	for(RuleGroupRef ref:ruleGroupRefList){
        		ref.setId(null);
        		ref.setManageId(newRuleManage.getId());
        		ref.setVersion(newRuleManage.getVersion());
        	}
        	this.ruleGroupRefService.insertBatch(ruleGroupRefList);

        	// 版本以及输入输出数据信息 需要重新保存
        	//简易规则集容器
            SimpleRuleGroup simpleRuleGroup = new SimpleRuleGroup();
            simpleRuleGroup.setRuleManage(newRuleManage);

            //查询老版本规则
            RuleGroup ruleGroup = new RuleGroup();
            ruleGroup.setManageId(newRuleManage.getId());
            ruleGroup.setVersion(newRuleManage.getVersion());
            List<RuleGroup> ruleList = this.ruleGroupRefService.findRefRuleManage(ruleGroup);
            List<RuleEditEntity> rules = new ArrayList<>();
            for(RuleGroup rg:ruleList) {
            	RuleManage rm = new RuleManage();
            	rm.setId(rg.getManageId());
    			rm.setName(rg.getRuleName());
    			rm.setProjectCode(rg.getProjectCode());
    			rm.setVersion(rg.getVersion());

    			RuleGroup newRG = new RuleGroup();
    			newRG.setManageId(rm.getId());
    			newRG.setVersion(rm.getVersion());
    			List<RuleGroup> ruleGroups = this.findList(newRG);

    			RuleEditEntity entity = new RuleEditEntity();
    			entity.setRuleManage(rm);
    			entity.setRuleGroups(ruleGroups);
    			rules.add(entity);
            }
            simpleRuleGroup.setRules(rules);

        	this.saveOrUpdateRule(simpleRuleGroup);
    	}
	}


	@Override
    public void copyRuleItem(RuleGroupInfo ruleGroupInfo) throws BizException {
    	String copyRuleManageId = ruleGroupInfo.getCopyRuleManageId();
    	String copyRuleVersion = ruleGroupInfo.getCopyRuleVersion();
    	String manageId = ruleGroupInfo.getManageId();
        if (!StringUtils.isEmpty(copyRuleManageId)) {
        	//查询关联关系
        	RuleManage ruleManage = this.ruleManageService.get(manageId);
        	RuleGroupRef condition = new RuleGroupRef();
        	// ruleId 中存储ruleMnageId，用于记录关联关系
        	condition.setRuleId(copyRuleManageId);
        	condition.setManageId(manageId);
        	condition.setVersion(ruleManage.getVersion());
        	List<RuleGroupRef> ruleGroupRefList = this.ruleGroupRefService.findList(condition);
        	if( ruleGroupRefList!=null && ruleGroupRefList.size()>0 ) {
        		// 此为关联关系
        		RuleGroupRef ruleGroupRef = ruleGroupRefList.get(0);
        		ruleGroupRef.setId(null);
        		ruleGroupRef.setRuleId(copyRuleManageId);
        		Integer salience = ruleManage.getCountSalience()==null?999999:ruleManage.getCountSalience()-1;
        		ruleGroupRef.setSort(salience);
        		this.ruleGroupRefService.save(ruleGroupRef);

//                try {
//	        		// 规则的ruleManage复制
//	        		Date date = new Date();
//	        		RuleManage rm = this.ruleManageService.get(copyRuleManageId);
//	                RuleManage newRuleManage = new RuleManage();
//	                newRuleManage.setName(rm.getName() + "_copy"+StringUtils.generateShortUuid());
//	                newRuleManage.setModelType(RuleModelTypeEnum.PolicyRuleGroup.code);
//	                newRuleManage.setProjectCode(ruleManage.getProjectCode());
//	                newRuleManage.setCreateDate(date);
//	                newRuleManage.setUpdateDate(date);
//	                newRuleManage.setRankRelationId(ruleManage.getRankRelationId());
//	                this.ruleManageService.saveOrUpdate(newRuleManage);
//	                dataModelService.saveOrUpdateBuiltinParam(newRuleManage.getCode(), newRuleManage.getName(), newRuleManage.getModelType(), newRuleManage.getProjectCode());
//
//	                String newManageId = newRuleManage.getId();
//
//	                RuleGroup con = new RuleGroup();
//	                con.setProjectCode(ruleManage.getProjectCode());
//	                con.setManageId(copyRuleManageId);
//	                List<RuleGroup> rgList = this.findList(con);
//	                List<RuleGroup> copyRGList = new ArrayList<>();
//	                for(RuleGroup rg:rgList) {
//	                	RuleGroup copyGroup = new RuleGroup();
//	                    BeanUtils.copyProperties(copyGroup, rg);
//	                    copyGroup.setId(null);
//	                    copyGroup.setManageId(newManageId);
//	                    copyGroup.setCreateDate(date);
//	                    copyGroup.setUpdateDate(date);
//	                    copyRGList.add(copyGroup);
//	                }
//
//                    this.insertBatch(copyRGList);
//
//                    ruleGroupRef.setId(null);
//            		ruleGroupRef.setRuleId(newManageId);
//            		Integer salience = ruleManage.getCountSalience()==null?999999:ruleManage.getCountSalience()-1;
//            		ruleGroupRef.setSort(salience);
//            		this.ruleGroupRefService.save(ruleGroupRef);
//
//            		ruleManage.setCountSalience(salience);
//            		this.ruleManageService.save(ruleManage);
//
//            		//关联数据复制
//            		ruleReferenceDataService.copyReferenceData(ruleManage, newRuleManage);
//                } catch (Exception e) {
//                    throw new BizException(e, "E-000000");
//                }
        	}
        }

    }

    @Override
    public List<RuleManageVO> findRuleGroupList(String currCode, String projectCode) {
        BaseModel ruleInfo = new BaseModel();
        ruleInfo.setModelType(RuleModelTypeEnum.PolicyRuleGroup.code);
        ruleInfo.setProjectCode(projectCode);
        List<RuleManageVO> list = this.ruleManageService.findRuleManageVO(ruleInfo);
        List<RuleManageVO> results = new ArrayList<RuleManageVO>();
        for (RuleManageVO tmpManage : list) {
            if (!tmpManage.getCode().equals(currCode)) {
                results.add(tmpManage);
            }
        }
        return results;
    }

    @Override
    public void transferRuleItem(String sourceRuleId,String sourceVersion, String targetCode, String projectCode) throws BizException {
    	//规则转移仅转移关联关系，即删除已有的关联关系，建立新的关联关系
        if (!StringUtils.isEmpty(targetCode) && !StringUtils.isEmpty(sourceRuleId)) {
            RuleManage ruleInfo = new RuleManage();
            ruleInfo.setCode(targetCode);
            ruleInfo.setProjectCode(projectCode);
            List<RuleManage> list = this.ruleManageService.findList(ruleInfo);
            if (list != null && list.size() > 0) {
                RuleManage ruleManage = list.get(0);
                RuleGroup ruleGroup = this.dao.get(sourceRuleId);
                if (ruleGroup != null) {
                	RuleGroupRef condition = new RuleGroupRef();
                	condition.setRuleId(ruleGroup.getId());
                	condition.setVersion(sourceVersion);
                	List<RuleGroupRef> sourceList = this.ruleGroupRefService.findList(condition);
                	if(sourceList!=null && sourceList.size() > 0) {
                		RuleGroupRef source = sourceList.get(0);
                		source.setManageId(ruleManage.getId());
                		source.setVersion(ruleManage.getVersion());
                		this.ruleGroupRefService.save(source);
                		ruleGroup.setVersion(ruleManage.getVersion());
                		ruleGroup.setUpdateDate(new Date());
                		this.save(ruleGroup);
                	}
//                    RuleGroup newRuleGroup = new RuleGroup();
//                    try {
//                        BeanUtils.copyProperties(newRuleGroup, ruleGroup);
//                        newRuleGroup.setId(null);
//                        newRuleGroup.setVersion(ruleManage.getVersion());
//                        newRuleGroup.setManageId(ruleManage.getId());
//                        newRuleGroup.setCreateDate(new Date());
//                        newRuleGroup.setUpdateDate(new Date());
//                        this.save(newRuleGroup);
//                        this.delete(ruleGroup);
//                    } catch (Exception e) {
//                        throw new BizException(e, "E-000000");
//                    }
                }
            }
        }

    }

    @Override
    public void returnRuleSetVersion(String manageId, String oldVersion) throws BizException {
        RuleManage ruleManage = this.ruleManageService.get(manageId);

        ruleManage.initVersion();
        RuleGroup groupInfo = new RuleGroup();
        groupInfo.setVersion(oldVersion);
        groupInfo.setManageId(manageId);
        List<RuleGroup> list = this.findList(groupInfo);
        for (RuleGroup ruleGroup : list) {
            ruleGroup.setId(null);
            ruleGroup.setVersion(ruleManage.getVersion());
            this.save(ruleGroup);

        }
        this.ruleManageService.save(ruleManage);

    }


    public  String   exportRuleExc(String projectCode,String  xml ) {
        String uploadRoot = Global.getConfig("file.uploadRoot");
        String uploadPath = uploadRoot + "/" + projectCode + RuleTest.RULE_GROUP_TEST;
        File  tmpFile = new  File(uploadPath);
        if (!tmpFile.exists()) {
        	tmpFile.mkdirs();
        }
        String  filePath  =  uploadPath+"/"+UUID.randomUUID()+".xlsx";
        File  file   = new  File(filePath);

		Workbook wb = null;
		FileOutputStream readfout = null;
		try {
		    readfout = new FileOutputStream(file);
	        wb = new XSSFWorkbook();
	        Sheet sheet =wb.createSheet("规则");
	        List<RuleExecParam> drList = this.execDrl(projectCode, xml);
	        Row  row = sheet.createRow(0);
	        Cell cell =row.createCell(1);
	        cell.setCellValue("规则测试");
	        row  = sheet.createRow(1);
	        cell =row.createCell(0);
	        cell.setCellValue("规则名称");
	        cell =row.createCell(1);
	        cell.setCellValue("执行时间");
	        RuleExecParam  execParam = null;
	        Row  tRow;
	        for( int  i =0;i<drList.size();i++) {
	        	execParam = drList.get(i);
	        	tRow =sheet.createRow(i+2);
	        	cell  = tRow.createCell(0);
	        	cell.setCellValue(execParam.getName());
	        	cell  = tRow.createCell(1);
	        	cell.setCellValue(execParam.getExecTime());
	        }
	        wb.write(readfout);
		}catch(Exception e) {
			e.printStackTrace();
			throw new BizException(e, "");
		}finally {
			if (readfout !=null) {
				try {
					readfout.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new BizException(e, "");
				}
			}
			if (wb != null)
				try {
					wb.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new BizException(e, "");
				}
		}
		return  filePath;
    }

    private   List<RuleExecParam>  execDrl(String  projectCode,String xml) throws Exception{
//        RuleVersioninfo  info  = new RuleVersioninfo();
//        info.setProjectCode(projectCode);
//        info.setModelType(RuleModelTypeEnum.GeneralRule.code);
//        List<RuleVersioninfo> list = this.ruleVersioninfoService.findNewPublishVersionList(info);
    	List<RuleVersioninfo>  list = new  ArrayList<>();
    	RuleManage  ruleInfo  = new  RuleManage();
    	ruleInfo.setProjectCode(projectCode);
    	ruleInfo.setModelType(RuleModelTypeEnum.GeneralRule.code);
    	List<RuleManage> rList =this.ruleManageService.findList(ruleInfo);
    	RuleVersioninfo  ruleVer = null;
    	for (RuleManage  ruleManage:rList) {
    		ruleVer = new  RuleVersioninfo();
    		ruleVer.setModelCode(ruleManage.getCode());
    		ruleVer.setModelName(ruleManage.getName());
    	    ruleVer.setRuleContent(this.getRuleDrl(ruleManage));
    	    list.add(ruleVer);
    	}
        Map<String, MClass> metaMap= this.dataBomService.findMapClass(projectCode);
        Map<String, Object> insertMap = RuleBomMapJsonConvert.json2bom(xml, metaMap);
        String  funcStr = this.ruleCodeblockService.getEffectiveFunc(projectCode);
        Map<String,String> funMap  = new  HashMap<>();
        funMap.put(projectCode, funcStr);
        List<RuleExecParam> drList  = new  ArrayList<>();
        RuleExecParam  execParam  = null;
        for (RuleVersioninfo verInfo :list) {
             execParam = new  RuleExecParam();
             execParam.setCode(verInfo.getModelCode());
             execParam.setName(verInfo.getModelName());
             execParam.setRuleContent(verInfo.getRuleContent());
             drList.add(execParam);
        }
        DroolsExcuteDrlUtils exdu = new  DroolsExcuteDrlUtils();
        exdu.setProjectCode(projectCode);
        exdu.setFuncMap(funMap);
        exdu.excuteDrlFile(insertMap,drList,metaMap);
        return  drList;
    }


    public  void   makeInserMapJson(String projectCode) {
    	Map<String, MClass> metaMap= this.dataBomService.findMapClass(projectCode);
        Map<String,Map<String,Object>> rr = new HashMap<>();
        for ( String  str: metaMap.keySet()) {
        	MClass  clazz = metaMap.get(str);
        	rr.put(str, new HashMap<>());
        	if (clazz != null) {
        	    for (Map.Entry<String, MField> enty:clazz.getFieldMap().entrySet()) {
        	    	   MField field = enty.getValue();
        	    	   if (field.getIsCollections().equals("true")) {
        	    		   rr.get(str).put(field.getName(),new ArrayList<>());
        	    	   }else if (field.getType().equals("String")) {
        	    		   rr.get(str).put(field.getName(),"");
        	    	   }else {
        	    		   rr.get(str).put(field.getName(),0);
        	    	   }


        	    }
        	}
        }
    }

	@Override
	public List<RuleGroup> findEffectRuleList(RuleGroup ruleGroup) {
		return this.dao.findEffectRuleList(ruleGroup);
	}

	@Override
	public void clearVersion(RuleManage ruleManage,List<String> versions) {
		if(RuleModelTypeFileEnum.PolicyRuleGroup.type.equals(ruleManage.getModelType())) {
	         this.ruleEntryService.deleteByMutilVersion(ruleManage, versions);
	         this.ruleGroupRefService.deleteByMutilVersion(ruleManage, versions);
		}else if(versions!=null&&versions.size()>0) {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("projectCode", ruleManage.getProjectCode());
			map.put("manageId", ruleManage.getId());
			map.put("versions", versions);
			this.dao.deleteByMutilVersion(map);
			DataCache.ruleSetEffectChange(ruleManage.getProjectCode());
		}
	}

	/**
	 * 打开条目列表,获取条目列表信息
	 */
	@Override
	public ResponseTable<RuleEntry> getEntryInfoByReq(RuleEntryReq ruleEntryReq, String type) throws Exception {
	  	//规则集manageId
    	String manageId = ruleEntryReq.getManageId();
    	String rankRelationId =ruleEntryReq.getRankRelationId();
    	String version = ruleEntryReq.getVersion();
    	String temp = ruleEntryReq.getTemp();
    	String projectCode = ruleEntryReq.getProjectCode();
    	if (StringUtils.isEmpty(manageId)) {
            throw new BizException("ID为空");
        }
        RuleManageVO ruleManage = new RuleManageVO();
        Map<String, Object> parmMap = new HashMap<String, Object>();
        parmMap.put("id", manageId);
        List<RuleManageVO> vList = this.ruleManageService.findRuleManageVO(parmMap);
        if (vList == null || vList.size() == 0) {
        	RuleManage tmp = ruleManageService.findByCode(manageId, projectCode);
        	if(tmp==null){
        		  throw new BizException("");
        	}else{
        		BeanUtils.copyProperties(ruleManage, tmp);
        	}
        }else{
        	ruleManage = vList.get(0);
        }

        RuleEntry ruleEntry = (RuleEntry)ruleEntryReq;
        ruleEntry.setGroupType(type);
        RuleGroup ruleGroup = new RuleGroup();
        ruleGroup.setManageId(ruleManage.getId());
        if (StringUtils.isEmpty(version)) {
        	ruleGroup.setVersion(ruleManage.getVersion());
        	ruleEntry.setVersion(ruleManage.getVersion());
            if("1".equals(temp)) {
            	ruleEntry.setVersion(ruleManage.getActiveVersion());
            	ruleGroup.setVersion(ruleManage.getActiveVersion());
    		}
        } else {
        	ruleGroup.setVersion(version);
        	ruleEntry.setVersion(version);
        }
        List<RuleEntry> ruleEntryList = this.ruleEntryService.findList(ruleEntry);
//        if(ruleEntryList==null||ruleEntryList.size()==0) {
//        	ruleEntry.setVersion(null);
//        	ruleEntryList = this.ruleEntryService.findList(ruleEntry);
//        }
        List<RuleGroup> ruleList = this.ruleGroupRefService.findRefRuleManage(ruleGroup);
        Map<String,String> mapNames = new HashMap<String,String>();
        for(RuleGroup rg:ruleList) {
        	String name=mapNames.get(rg.getEntryId());
        	if(StringUtils.isEmpty(name)) {
        		mapNames.put(rg.getEntryId(), rg.getRuleName());
        	}else {
        		mapNames.put(rg.getEntryId(), name+","+rg.getRuleName());
        	}
        }
        for(RuleEntry re:ruleEntryList) {
        	re.setRuleNames(mapNames.get(re.getId()));
        }

        PageInfo<RuleEntry> pageinfo = new PageInfo<>(ruleEntryList);
        ResponseTable<RuleEntry> res = new ResponseTable<>(pageinfo);
        return res;
	}

    /**
     * 打开条目,获取条目信息
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
	@Override
	public ResponseTable<RuleGroup> openRuleEntryView(RuleGroupInfo ruleGroupInfo) throws IllegalAccessException, InvocationTargetException {
    	String type = ruleGroupInfo.getType();
    	String entryId = ruleGroupInfo.getEntryId();
    	String version = ruleGroupInfo.getVersion();
    	String temp = ruleGroupInfo.getTemp();
    	String manageId = ruleGroupInfo.getManageId();
    	String rankRelationId = ruleGroupInfo.getRankRelationId();
    	String projectCode = ruleGroupInfo.getProjectCode();

    	if (StringUtils.isEmpty(manageId)) {
            throw new BizException("ID为空");
        }

        RuleManageVO ruleManage = new RuleManageVO();
        Map<String, Object> parmMap = new HashMap<String, Object>();
        parmMap.put("id", manageId);
        List<RuleManageVO> vList = this.ruleManageService.findRuleManageVO(parmMap);
        if (vList == null || vList.size() == 0) {
        	RuleManage tmp = ruleManageService.findByCode(manageId,projectCode);
        	if(tmp==null){
        		  throw new BizException("");
        	}else{
        		BeanUtils.copyProperties(ruleManage, tmp);
        	}
        }else{
        	ruleManage = vList.get(0);
        }
        RuleEntry entry = ruleEntryService.get(entryId);

        RuleGroup ruleGroup = (RuleGroup)ruleGroupInfo;
        ruleGroup.setManageId(ruleManage.getId());
        ruleGroup.setEntryId(entry.getId());
        if (StringUtils.isEmpty(version)) {
            ruleGroup.setVersion(ruleManage.getVersion());
            if("1".equals(temp)) {
            	ruleGroup.setVersion(ruleManage.getActiveVersion());
    		}
        } else {
            ruleGroup.setVersion(version);
        }
        // 从关联表中查询出ruleGroup
        List<RuleGroup> ruleList = this.ruleGroupRefService.findRefRuleManage(ruleGroup);
    	PageInfo<RuleGroup> pageInfo = new PageInfo<>(ruleList);
    	ResponseTable<RuleGroup> res = new ResponseTable<>(pageInfo);
		return res;
	}
}
